jQuery 检查联系表格中电子邮件地址的格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10178268/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 08:54:44  来源:igfitidea点击:

Checking the format of an email address in a contact form

jqueryformsemail

提问by Andy

I'm using a simple form with a name, email and comment field to send messages from a webpage. There's a hidden title field as well which should be empty in order for the form to be submitted - spam protection if you like.

我正在使用一个带有姓名、电子邮件和评论字段的简单表单来从网页发送消息。还有一个隐藏的标题字段,它应该是空的,以便提交表单 - 如果您愿意,可以防止垃圾邮件。

The JQuery code I am running the form through before submitting works ok, but is currently only looking for an "@" character in the email address field. What I want is a better check for a correctly formatted email address.

我在提交之前运行表单的 JQuery 代码工作正常,但目前只在电子邮件地址字段中查找“@”字符。我想要的是更好地检查格式正确的电子邮件地址。

Here's the code.

这是代码。

    $(function() {  
    $('.error').hide();  
    $(".button").click(function() {  
    // validate and process form here  

        $('.error').hide();  
        var name = $("input#name").val();  
            if (name == "") {  
            $("label#name_error").show();  
            $("input#name").focus();  
            return false;
        }  
        var email = $("input#email").val();  
            if (!(email.indexOf('@') > 0)) {
            $("label#email2_error").show();  
            $("input#email").focus();  
        return false;  
        }  
        var message = $("textarea#message").val();  
            if (message == "") {  
            $("label#message_error").show();  
            $("textarea#message").focus();  
        return false;  
        } 
        var title = $("input#title").val()
            if(title !== "") {  
            $("input#title").focus();  
        return false;  
        } 

    var dataString = 'name='+ name + '&email=' + email + '&message=' + message;  
    //alert (dataString);return false;  
    $.ajax({  
        type: "POST",  
        url: "sendmail.php",  
        data: dataString,  
        success: function() {  
            $('#message_form').html("<div id='response'></div>");  
            $('#response').html("<div id='content_success_block' class='shadow_box'>")  
                .append("<div id='success_image'><img src='assets/misc/success.png'></div>")
                .append("<div id='success_text'>Thanks for contacting us! We will be in touch soon.</div>")
                .append("</div>")                   
            .hide()  
            .fadeIn(2500, function() {  
                $('#response');  
            }); 
        }  
    });  
    return false; 
    });

});

Any help is appreciated.

任何帮助表示赞赏。

回答by SpYk3HH

The one that has worked best for "me"

最适合“我”的那个

function validEmail(v) {
    var r = new RegExp("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?");
    return (v.match(r) == null) ? false : true;
}


?Important!

?重要的!

You should really read THIS. It provides a lot of information on Regex for Emails, and why there is not really a good "be all, end all" solution. In short, you have to determine what is best for your expected users.

你真的应该阅读这个。它提供了大量关于电子邮件正则表达式的信息,以及为什么没有一个真正好的“全部结束”解决方案。简而言之,您必须确定什么最适合您的预期用户。



Incorperated

合并

}  
var email = $("input#email").val();  
if (!validEmail(email)) {
    $("label#email2_error").show();  
    $("input#email").focus();  
    return false;  
}  

Alternate Strategy you might try: I tend to check email on keypress timeout(thus allowing the ability to fade out submit button if not all fields are ready)

您可以尝试的替代策略:我倾向于在按键超时时检查电子邮件(因此如果不是所有字段都准备好,则允许淡出提交按钮的能力)

回答by QasimRamzan

Call that function onBlur event of that text box, where you want to chk a valid email.

调用那个文本框的 onBlur 事件函数,你想在那里查出一个有效的电子邮件。

 function validateForm()
{
 var x = document.getElementById('txtEmail');
 var atpos=x.value.indexOf("@");
 var dotpos=x.value.lastIndexOf(".");
 if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
  {
    alert("Not a valid e-mail address");
    return false;
  }
}

回答by Hymanotonye

Just Stating a more obvious function that returns true or false when the email value is tested. Using the regExp.test(value)

只是说明一个更明显的函数,在测试电子邮件值时返回 true 或 false。使用regExp.test(value)

 var emailIsValid =  function(value){
        var regex = new RegExp ("^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$");
        return regex.test(value);
    }

var email = $("input#email").val();  
        if (!emailIsValid(email)) {
           $("label#email2_error").show();  
           $("input#email").focus();  
        return false;  
        }  

回答by timmz

The problem with Regex above (SpYk3HH) is that it validats somthing like: [email protected]i think the best way is to use some ajax to call a PHP function (if you use PHP indeed) something like this:

上面的正则表达式(SpYk3HH)的问题在于它验证了类似的东西:[email protected]我认为最好的方法是使用一些ajax来调用PHP函数(如果你确实使用PHP)是这样的:

if(!filter_var($email, FILTER_VALIDATE_EMAIL))
echo "Email Not Valid ! ";