使用jquery对多个表单进行常见电子邮件验证

时间:2013-08-13 10:10:42

标签: javascript jquery html5

我有一张表格

<form id="Register" method="post" onsubmit="return validateForm()">
     <p><label>Your Email</label><input type="text" name="email"/></p>
     <p style="margin-left:27%;"><input type="submit" name="submit" value="Submit" /></p>
</form>

我使用此表单的javascript验证是

function validateForm() {
var x = document.forms["Register"]["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;
}
}

我有两个或更多表格

 <form id="Login" method="post" >
    <p><label>Email</label><input type="text" name="Log_email" /></p>
    <p style="margin-left:27%;"><input type="submit" name="submit" value="Login" /></p>
 </form>

<form id="forgot" method="post">
<p><label>Your Email</label><input type="text" name="email"/></p>
<p style="margin-left:27%;"><input type="submit" name="submit" value="Submit" /></p>
</form>

如何为所有这些表格重写javascript验证。

3 个答案:

答案 0 :(得分:1)

JSFIDDLE:http://jsfiddle.net/g2frB/1/

JS CODE:

$(".emlfrm").on("submit",function()
 {
        var x = $(this).find(".eml").eq(0).val();
        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;
        }         
 });

HTML CODE:

<form class="emlfrm" id="Login" method="post" >
    <p><label>Email</label><input type="text" class="eml" name="Log_email" /></p>
    <p style="margin-left:27%;"><input type="submit" name="submit" value="Login" /></p>
 </form>

<form class="emlfrm" id="forgot" method="post">
<p><label>Your Email</label><input type="text" class = "eml"name="email"/></p>
<p style="margin-left:27%;"><input type="submit" name="submit" value="Submit" /></p>
</form>

答案 1 :(得分:1)

如果您在所有表单中使用相同的电子邮件名称,而不是使用所有表单中的'this.id'参数调用验证函数

onsubmit="return validateForm(this.id)"

并修改代码:

function validateForm(id) {
var x = document.forms[id]["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;
}
}

答案 2 :(得分:0)

在您的电子邮件字段中添加一个类并验证此项