I need a way to submit a form only if email is valid. If email is NOT valid then show ONLY an alert ( below you can see my code ).
JAVASCRIPT:
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function continueornot() {
if(validateEmail(document.getElementById('emailfield').value)){
// ok
}else{ alert("email not valid"); return false;}
}
HTML:
<form method="post" action="register.php" enctype="multipart/form-data">
<table>
<tr><td>Email:</td></tr>
<tr><td><input type="text" size="30" name="email" id="emailfield"> </td></tr>
<tr><td>Password:</td></tr>
<tr><td><input type="password" size="30" name="password"> </td></tr>
</table>
<input name="steptwo" value="Create Account" type="submit" onclick="continueornot();"/>
</form>
The problem is that the form is submitted even if the email is NOT valid.
How can I resolve this problem ?
You should attach return continueornot();
to the onsubmit
event of the form, not the button's click event.
See this fiddle: http://jsfiddle.net/NdSmu/
You need the return value.
function continueornot() {
if(validateEmail(document.getElementById('emailfield').value)){
// ok
return true;
}else{ alert("email not valid"); return false;}
}
onclick="return continueornot();"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With