I wrote a Javascript to validate my forms before submission. The function of the Javascript is to prevent my form from submitting itself when a user provides a phone number that matches with the result in my Javascript but rather shows an error message that says "Phone number already used!"
My problem is that the validation works fine: Users get an alert that the phone number they provided has been used but my form still submits itself after showing the error message.
What am I not doing rightly?
Below is my code.
function check(form) /*function to check used phone number*/ {
/*the following code checkes whether the entered phone number is matching*/
if (form.phonenum.value == "0807575566464"
|| form.phonenum.value == "09057487463")
{
alert("Phone number used! provide a new one! \n") /*displays error message*/
} else if (form.phonenum.value.length<11 || form.phonenum.value.length>11) { alert("Phone number should be 11 digits! \nAnd it should begin with; 080, 081, 070, 090, or 091.");
}
else {
return false;
}
}
<form action='' method='POST' enctype="multipart/form-data" id="formName">
<input type="text" id="phonenum" name="myinput">
<button href='/' type='submit' onclick="check(this.form)">Submit</button>
</form>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
I think you need to add e.preventDefault() in order for it to stop reloading the page when you hit submit.
CodePudding user response:
You need to bind a function to the onsubmit event and stop the event if the validaiton fails.
HTML:
<form action='' method='POST' enctype="multipart/form-data" id="formName" onsubmit="validateForm(event)">
JavaScript:
function validateForm(event) {
if(validation fails...) {
event.preventDefault();
....
}
}
Documentation and examples for the preventDefault function: https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
Instead of using event.preventDefault() you could also just return false:
https://stackoverflow.com/a/65538474/9441244
In your case your JavaScript should look like this
HTML:
<form action='/test/' method='POST' enctype="multipart/form-data" id="formName" onsubmit="validateForm(event)">
<input type="text" id="phonenum" name="myinput">
<button href='/' type='submit'>Submit</button>
</form>
JavaScript:
function validateForm(event) {
if (this.phonenum.value == "0807575566464" || this.phonenum.value == "09057487463") {
event.preventDefault();
alert("Phone number used! provide a new one! \n");
} else if (this.phonenum.value.length != 11) {
this.preventDefault();
alert("Phone number should be 11 digits! \nAnd it should begin with; 080, 081, 070, 090, or 091.");
}
}