jQuery验证电子邮件验证问题

问题描述 投票:5回答:1

我正在尝试排除故障并修复我的电子邮件验证无法正常工作的原因。假设检测到无效的电子邮件:它有太多......(点),除了欧洲地址([email protected])以及[email protected]之外。但是现在它除了一个点外,如果只要你没有添加(。)点就没有完成打字,只要它有@。有人请帮我解决我的错误吗?

<script>
     $("#form").validate({
    rules: {
        firstname_1: {
            required: true
        },
        email_1: {
            required: true,
            email: true
        },
        // Same for other fields
    },
    messages: {
        firstname_1: "This field is required.",
        email_1>: "Please enter valid email address.",
        // Repeat for other fields
    }
});
function isValidEmail(email_1)
{
    return /^[a-z0-9]+([-._][a-z0-9]+)*@([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,4}$/.test(email_1)
        && /^(?=.{1,64}@.{4,64}$)(?=.{6,100}$).*/.test(email_1);
}
</script>
jquery regex jquery-validate
1个回答
9
投票

假设您已经拥有正确的验证逻辑和/或正则表达式,那么您需要使用the .addMethod() method创建自己的规则。

$("#form").validate({
    rules: {
        firstname_1: {
            required: true
        },
        email_1: {
            required: true,
            myEmail: true  // <- declare your custom rule
        },
        // Same for other fields
    },
    messages: {
        firstname_1: "This field is required.",
        email_1: "Please enter valid email address.",
        // Repeat for other fields
    }
});

// create your custom rule
jQuery.validator.addMethod("myEmail", function(value, element) {
    return this.optional(element) || /* your regex boolean logic goes here */;
}, 'Please enter valid email address.');

注意:您在messages中的字段名称上也有语法/拼写错误。应该是email_1,而不是email_1>

See this answer正确使用.addMethod()

© www.soinside.com 2019 - 2024. All rights reserved.