The validation works, and the alert pops up when the email address is not valid, but then it goes and submits it after you click 'Ok' anyway. How do I stop it from processing the action?
Code sample:
<input type="submit" onclick="validate()" />
function validate() {
var email = $('input[name=email]').val();
if (!/(.+)@(.+){2,}\.(.+){2,}/.test(email)) {
alert('Please enter a valid email address');
return false;
}
}
Thanks!
The validation works, and the alert pops up when the email address is not valid, but then it goes and submits it after you click 'Ok' anyway. How do I stop it from processing the action?
Code sample:
<input type="submit" onclick="validate()" />
function validate() {
var email = $('input[name=email]').val();
if (!/(.+)@(.+){2,}\.(.+){2,}/.test(email)) {
alert('Please enter a valid email address');
return false;
}
}
Thanks!
Share Improve this question asked Sep 21, 2012 at 2:16 zenkatyzenkaty 1,5489 silver badges11 bronze badges 5-
(.+){2,}
--- what does this part mean? – zerkms Commented Sep 21, 2012 at 2:18 - I got the regex from somewhere else, sorry, I don't know the specifics of it, only that it validates the email! My guess is that it's something like "must be something here, must be at least 2 characters" – zenkaty Commented Sep 21, 2012 at 2:19
- 1 <input type="submit" onclick="return validate()" /> – gp. Commented Sep 21, 2012 at 2:20
-
So should I use
.+@.{2,}\..{2,}
instead of(.+)@(.+){2,}\.(.+){2,}
? – zenkaty Commented Sep 21, 2012 at 2:42 -
@zenkaty: yeb, because the latter makes no sense.
(.+){2,}
--- this could only be written by a person who doesn't understand what he does – zerkms Commented Sep 21, 2012 at 2:43
2 Answers
Reset to default 4onclick="return validate();"
then return true
if validation is successful and false
if not...
you can also attach the validation to the form itself:
<form onsubmit="return validate();">
or with jquery:
$('form').submit(function() {
// validate
});
You need to bind onsubmit event of the form tag i.e.
<form onsubmit="return validate();" >...</form>