I gift free tickets to students for free entry into a training class and I write each student's phone number on their ticket to prevent another student from using a stolen ticket for entry.
I am trying to design a form for the students to register as candidates and also to have their data.
On the form, I want them to input their phone number and the unique code that is printed on the ticket that I gifted to them.
I am trying to make only students with my ticket be able to submit the form.
How do I prevent form submission with javascript when the phone number and the ticket number do not match?
Below is a sample of a javascript that I use to prevent form submission when email does not match.
I am aware that the sample below is not the best solution but I still need the solution. Thanks.
Code Sample;
function check_email()
{
var email = document.getElementById("email").value;
if(email.localeCompare("[email protected]" || "[email protected]")) {
alert("ATTENTION! \nThe email address that you provided did not match with the email that is associated.");
return false;
}
return true;
}
<form action='' onsubmit="return check_email();">
<input type="password" name="email" placeholder="go*****b@*****.com" required='' id="email"/>
<button href='/' type='submit' id="submitForm">Submit</button> <button type="reset" value="Cancel">Reset</button>
</form>
CodePudding user response:
As from the comments, I acknowledged that you already have the data of pairs written well in a book. Then, you can write them all into array of pairs (array of json).
var data = [{phone: '08012345678', ticket: 'ACTF'}, {phone: '08012345679', ticket: 'ACTG'}];
// set false default
document.querySelector('form').addEventListener('submit', function (e)
{
var phNumber = document.getElementById("phone").value;
var scTicket = document.getElementById("ticket").value;
var isMatch = false;
// check if any same
for(var i=0; i<data.length; i ) {
// If same, proceed submit.
if (data[i].phone === phNumber && scTicket === data[i].ticket){
isMatch = true;
return true;
}
}
//if the validator check fails, prevent the form from being submitted
if(isMatch == false){
e.preventDefault();
alert('Not match!');
}
});
<form action='post' >
<input type="text" name="phone" placeholder="Phone Number" required='true' id="phone"/>
<input type="password" name="ticket" placeholder="Secret Ticket Code" required='true' id="ticket"/>
<button href='/' type='submit' id="submitForm">Submit</button> <button type="reset" value="Cancel">Reset</button>
</form>
CodePudding user response:
You might want to use event.preventDefault()
(check this question: JavaScript code to stop form submission