如何在javascript中验证电子邮件

时间:2016-03-28 07:23:25

标签: javascript validation email asp.net-mvc-5

我正在开发一个mvc 5项目。联系我们页面我希望用户发送管理员他/她的电子邮件地址。所以我想在该页面上用javascript验证电子邮件。我写了一些无效的代码。我希望你能帮我解决问题。

<script language="javascript">
    function f1() {
        var inputText = document.getElementById("email").value;
        var mailformat = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        if (inputText.value.match(mailformat)) {
            document.form1.text1.focus();

        }
        else {
            alert("You have entered an invalid email address!");
            document.form1.text1.focus();
            event.preventDefault();
        }
    }
</script>

4 个答案:

答案 0 :(得分:0)

function validateEmail(email) {
    var re = ([\w-+]+(?:\.[\w-+]+)*@(?:[\w-]+\.)+[a-zA-Z]{2,7});
    return re.test(email);
}

答案 1 :(得分:0)

这里给出了使用JS验证电子邮件的基本HTML和JS工作代码,用于u -

&#13;
&#13;
function validateForm()
{
    var x = document.forms["myForm"]["email"].value;
    var atpos = x.indexOf("@");
    var dotpos = x.lastIndexOf(".");
    if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
    {
        alert("Not a valid e-mail address");
        return false;
    }
    else
    {
        alert("Valid e-mail address");
        return true;
    }
}
&#13;
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm();" method="post">
    Email: <input type="text" name="email">
    <input type="submit" value="Submit">
</form>
&#13;
&#13;
&#13;

想想,你有答案:)

答案 2 :(得分:0)

<form name="form" action="#" onSubmit="return f1()" method="POST">
    <input type="email">
</form>
<script>
function f1(){
    var email = document.forms["form"]["Email"].value;
    var regex = /^([0-9a-zA-Z]([-_\\.]*[0-9a-zA-Z]+)*)@([0-9a-zA-Z]([-_\\.]*[0-9a-zA-Z]+)*)[\\.]([a-zA-Z]{2,9})$/;
    if(!regex.test(email)){
        alert("You have entered an invalid email address!");
        return false;
    }
}  
</script>       

答案 3 :(得分:0)

您不希望inputText.value只有inputText这样

&#13;
&#13;
<input type="text" id="email" />
<input type="submit" onClick="f1()"/>


<script language="javascript">
    function f1() {
        console.log(document.getElementById("email").value);
        var inputText = document.getElementById("email").value;
      console.log(inputText)
        var mailformat = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        if (inputText.match(mailformat)) { // <<<<<<< here
            //document.form1.text1.focus();
            alert("correct")

        }
        else {
            alert("You have entered an invalid email address!");
            document.form1.text1.focus();
            event.preventDefault();
        }
    }
</script>
&#13;
&#13;
&#13;

相关问题