使用正则表达式验证电子邮件 [英] validate email with regex jquery
本文介绍了使用正则表达式验证电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
提及此问题:
<form id="new_invitation" class="new_invitation" method="post" data-remote="true" action="/invitations" accept-charset="UTF-8">
<div id="invitation_form_recipients">
<input type="text" value="" name="invitation[recipients][]" id="invitation_recipients_0"><br>
<input type="text" value="" name="invitation[recipients][]" id="invitation_recipients_1"><br>
<input type="text" value="" name="invitation[recipients][]" id="invitation_recipients_2"><br>
<input type="text" value="" name="invitation[recipients][]" id="invitation_recipients_3"><br>
</div>
<input type="submit" value="Send invitation" name="commit">
</form>
使用jquery为字段设置最小长度的代码吗?
Code for set a minimum length for a field with jquery?
$('#new_invitation').submit(function(event) {
if ($('#invitation_form_recipients input').filter(function() {
return $(this).val();
}).length == 0) {
// all the fields are empty
// show error message here
// this blocks the form from submitting
event.preventDefault();
}
});
我如何通过jquery验证每个字段输入都具有有效的电子邮件地址?在上面的代码中?
谢谢!
$('#new_invitation').submit(function(e) {
$('#invitation_form_recipients input').each(function(e) {
email_address = $(this);
email_regex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i;
if(!email_regex.test(email_address.val())){ alert('this is not valid email'); e.preventDefault(); return false; }
});
});
推荐答案
You probably want to use a regex like the one described here to check the format. When the form's submitted, run the following test on each field:
var userinput = $(this).val();
var pattern = /^\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i
if(!pattern.test(userinput))
{
alert('not a valid e-mail address');
}
这篇关于使用正则表达式验证电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文