最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Stop form from submitting when it doesn't validate - Stack Overflow

programmeradmin2浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 4
onclick="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>
发布评论

评论列表(0)

  1. 暂无评论