I am using the following javascript code to validate an input email address from a user. My problem is, I am using html5 for 'email' typed textbox which at present won't work fine on latest IE versions. I find myself in love with html5 better since it offers better look-and-feel effects. I thus would like to use it and so at the same time would need to add in a little snippet to check for IE browsers as in the following code,
function IsValidEmail(email)
{
var em= new RegExp(/^[+a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);
return em.test(email);
}
$("#aspformblahblah").submit(function()
{
var em=$('#email').val();
if(!IsValidEmail(em))
{
if($.browser.msie)
{
$("#e-valid").css({'color':'red','padding-left':'5px', 'font-style':'italic'});
$("#e-valid").html("Please enter a valid email address");
return false;
}
}
return true;
});
It works fine on all other browsers, but my mind seems full to think up a logical mistake I am making somewhere along the line that the above code doesn't work on IE when the form is submitted. It validates the entered email address well, though. Any idea to enlighten me please.... Thank you very much,
Wrap in document.ready
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
function IsValidEmail(email) {
// the regex works in IE but should be a string (see nnnnn's answer)
// var em= new RegExp(/^[+a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);
var em=/^[+a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i; // simpler
return em.test(email);
}
$(document).ready(function() {
$("#form1").submit(function() {
var em=$('#email').val();
if(!IsValidEmail(em))
{
if($.browser.msie)
{
alert("Wrong email");
$("#e-valid").css({'color':'red','padding-left':'5px', 'font-style':'italic'});
$("#e-valid").html("Please enter a valid email address");
return false;
}
}
return true;
});
});
</script>
</head>
<body>
<form id="form1">
<input id="email" type="email" value="" /><span id="e-valid"></span><br/>
<input type="submit" />
</form>
</body>
</html>
You are passing a regex literal to the RegExp() constructor, but it expects a string. Try this:
function IsValidEmail(email)
{
var em= /^[+a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i;
return em.test(email);
}
Note that you don't need the variable em, and if you're using the "i" flag for a case insensitive regex then you can simplify your pattern:
return /^[+a-z0-9._-]+@[a-z0-9.-]+\.[a-z]{2,4}$/i.test(email);