validating email address fails

Go To StackoverFlow.com

1

I have a little problem concerning jquery and email validation. I am using an email typed input box to retrieve user's entered email address (html5) but it doesn't work on IE, I now would like to add in a simple jquery function to validate input email address before submitting the form. Here is what I have done.

    function IsValidEmail(email)
{
    var eReg=/^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    return eReg.test(email);
}
$(document).ready(function()
    {
    var em=$('#email').val();
    if(!IsValidEmail(em))
    {
        $('#e-valid').css('color','red');
            $('#e-valid').html("Email is invalid.Please enter a valid address");
    }
    }
);

and here is the form

<form method="POST" action="doit" id="stuff">
        <table>
        <tr>
            <td width="175px"><label for="email">Your email address</label></td>                
            <td><input type="email" name="email" id="email" size="35"/><span id="e-valid">&nbsp;</span></td>
        </tr>
        <tr>
            <td></td><td><input type="submit" value="Send" /></td>
        </tr>
        </table>
    </form>

However, nothing is being shown when I entered an invalid email address in the input box. I am thankful for any help. Thank you.

2012-04-04 02:10
by Dust Counters
If I understand correctly, when the html form is loaded and ready, then the code is run. After the html page is ready, then now you change the field, you need to trigger the check again which based on what you've pasted above, I can't find it - Jasonw 2012-04-04 02:20


2

You're validating the email on page load but not when the user submit the information. You should place your validation on submit event

$("#aspnetForm").submit(function(){
    var em=$('#email').val();
    if(!IsValidEmail(em))
    {
        $('#e-valid').css('color','red');
        $('#e-valid').html("Email is invalid.Please enter a valid address");
        return false;
    }
    return true;
}
2012-04-04 02:21
by Claudio Redi


0

First of all, the regex you're using looks weird. Most backslash-using placeholders lose their meaning inside a character set.

Please see this and this for information regarding regular expressions to use for the purpose of validating an email address.

After fixing the regex, you should follow Claudio's advise and place the validation on the form submission.

2012-04-04 02:24
by Ariel
Ads