使用jQuery进行电子邮件检查不起作用

Email check with jQuery doesn't work

本文关键字:检查 不起作用 电子邮件 jQuery 使用      更新时间:2023-09-26

我试图使Ajax形成并尝试在那里进行电子邮件验证。我找到了这个解决方案http://jsfiddle.net/EFfCa/

但无法在我的脚本中打开它:

<script> 
    $('#joinForm').ajaxForm(function() {
        var testEmail = /^[A-Z0-9._%+-]+@([A-Z0-9-]+'.)+[A-Z]{2,4}$/i;
        var name = $("input[name=name]")
        var email = $("input[name=email]")
        if(name.val()==''||email.val()=='') {
            $(".notify").show();
            $(".notify p").text('empty');
        } else if(testEmail.test(email.value)) {
            $(".notify").show();
            $(".notify p").text('email is wrong');      
        } else {
            $(".notify").show();
            $(".notify p").text('good');    
        }
    }); 
</script>

即使电子邮件错误,表单也始终通过验证。验证空字段效果很好...

如果

电子邮件正确,则以下行else if(testEmail.test(email.value))将返回 true。

在你的逻辑中,这就是电子邮件错误的地方,这可能是问题所在吗?

这是因为您的传递email.value. jquery对象没有名为 value 的参数,因此这将解析为 undefined

如果 .test() 未定义地通过,则返回 true,因此您的测试将始终通过。

请改用.val()

  $('input').blur(function() {
        var testEmail =/^(['w-]+(?:'.['w-]+)*)@((?:['w-]+'.)*'w['w-]{0,66})'.([a-z]{2,6}(?:'.[a-z]{2})?)$/i;
        if (testEmail.test(this.value)) alert('passed');
        else alert('failed');
    });