在jQuery中使用正则表达式验证电子邮件 [英] Validate email with a regex in jQuery

查看:78
本文介绍了在jQuery中使用正则表达式验证电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正在参考此问题:

如何我使用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为字段设置最小长度的代码是什么?

What would the code be for settting 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验证每个字段输入都具有有效的电子邮件地址?在上面的代码中?

推荐答案

您可能希望使用正则表达式,例如

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');
}​

这篇关于在jQuery中使用正则表达式验证电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆