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"> </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.
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;
}
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.