neel
neel

Reputation: 5293

Common Email validation for more than one forms using jquery

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

Answers (3)

Ankit Tyagi
Ankit Tyagi

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

sajawikio
sajawikio

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

Nikolay Ayrapetov
Nikolay Ayrapetov

Reputation: 304

Add a class to your email fields and verify this item

Upvotes: 0

Related Questions