0

我有一个表格

<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 验证。

4

3 回答 3

1

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

JS代码:

$(".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 代码:

<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>
于 2013-08-13T10:22:41.800 回答
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;
}
}
于 2013-08-13T10:44:03.587 回答
0

将课程添加到您的电子邮件字段并验证此项目

于 2013-08-13T10:27:07.297 回答