Reputation: 5293
i have a form
<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>
and i use the javascript validation for this form is
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;
}
}
i have two or more forms
<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>
how can i rewrite the javascript validation commonly for all these forms.
Upvotes: 0
Views: 4320
Reputation: 2375
If you are using same email name in all forms than call validate function with 'this.id' argument from all forms
onsubmit="return validateForm(this.id)"
and modify the code :
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;
}
}
Upvotes: 1
Reputation: 1514
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>
Upvotes: 1