A while ago I put up a Password Strength Checker using JavaScript and Regular Expressions. On that same note, you can also check the structure of an email address utilizing the same regular expression (regex) methodology.
If your form element has the id=”emailaddress” and you add a form onSubmit=”return checkEmail();“, this is a Javascript function that you can utilize to return an alert if the email address has a valid structure or not:
<script language="javascript"> function checkEmail() { var email = document.getElementById('emailaddress'); var filter = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; if (!filter.test(email.value)) { alert('Please provide a valid email address'); email.focus; return false; } } </script>
The function validates the contents of the email to that of the filter. If the comparison fails, it pops up an alert and returns the focus back to the email address field!
For forms with multiple email addresses, it would be good to do class=”emailaddress”. If you have the prototype.js library (http://www.prototypejs.org) included on the page you can do something like this:
var valid = true;
var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
$$(‘.emailaddress’).each( function(email) {
if (!filter.test(email.value)) {
alert(?Please provide a valid email address?);
email.focus;
valid = false;
}
});
return valid;
Thanks Ade! I’m going to need to learn some more about classes and JavaScript!
Doug’s original example was cool, but this one is freezing! I did not know that you could process elements having a class this manner, and the functional syntax is sweet.
Ade and his team are amazing!
Nice, I can always count on you for some wicked cool scripts! 🙂
Thanks Tony!
I like the idea, but I would be hesitant to adopt this particular regular expression without description of which legal email addresses it does not accept and which illegal addresses it permits.
For an example of a regular expression that does a decent job alongside an explanation of which cases it does not cover, see this:
http://www.regular-expressions.info/email.html
My personal preference is to cover most of the simple cases and issue a warning for everything else rather than rejecting it. If Bob really want sto submit bob@com.museum rather than bob@museum.com, why not let him?
Hi Reg,
You can test out the Regex utilizing an Online Regex Tester.
Also, there’s definitely much more that can be done if you want to ensure an email address is valid in accordance with the RFC.
There are a few reasons not to allow someone to enter an invalid email address:
1. They will get annoyed at you when the email they expected doesn’t get through – regardless of whether or not it was your fault the address was entered incorrectly.
2. If com.museum was a valid domain and, let’s say, Yahoo! operated it – any email address that bounced would have a negative impact on your company’s reputation for email delivery. This could lead to all of your company’s email being blocked.
3. If your email service provider allowed you to enter bob@com.museum, you’d also pay for each email sent to that email address until they unsubscribed that address due to bounces. I would steer clear of any ESP that would allow an invalid email address like that – they’re just taking your money!
Thanks for stopping by!
Doug
Perfect, just what I needed!
There’s much simpler way to write the expression:
var regex = /^[a-z0-9\._-]+@([a-z0-9_-]+\.)+[a-z]{2,6}$/i;
– With the final modifier /i there’s no need to indicate the upper case range.
– I don’t know of any TLD with numbers in it.
On a side note, I do allow TLD with up to 6 chars; new ones arrive regularly and you never know (well, somme future ones may even have numbers in it, I know).
Hi there,
I am tring to use this in an existing form in real-time, but this doesnt appear to be validating in realtime like your password strength checker…
Or, am i just that clueless, and it aint workin for me?
btw, I really like what you have going on here, your tutorials are very simple, I will definately be bookmarking this one….
Just an FYI; I haven’t tried Ade’s solution but the pattern above doesn’t validate e-mail addresses with apostrophes in them.. (eg, Mike.O’Hare@Whatever.com). Apostrophes are valid per the RFC 2821/2822 –> http://www.faqs.org/rfcs/rfc2822.html
HTH,
Sanjay
It also doesn’t appear to handle the plus character, which is valid.
See: http://www.dominicsayers.com/isemail/
On a larger note, this is a key problem with cutting-and-pasting code, one which deserves a full discussion in itself.
@robbyslaughter.com
you are nutz..
it's working fine..!@
Would be fine if we could find a solution to avoid fake e-mail addresses on comments on WordPress
Just a small correction: The regular expression has an extra ()+ at the end. It should read:
^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+[a-zA-Z0-9]{2,4}$
With the first one any length TLDs would be accepted (which is not intrinsecally wrong as others have pointed out, but if that was the intention the expression could be shortened).
Can you please explain the regular expression of this code and how its working? Also about .test – Is .test a default statement in javascript to check things like you did in the code above?
This is a short code for email expression-
function validateEmail(id)
{
var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$/;
return emailPattern.test(id);
}
Deepak Rai
varanasi
This is a short code for email expression-
function validateEmail(id)
{
var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$/;
return emailPattern.test(id);
}
Deepak Rai
varanasi
Thanks a lot uncle. That helped me a lot 🙂
Amanda
thanks for the code !
Thanks, but there is an error in this regex. I'm not a regex expert, but I tried email:
test@test
and it passed the regex… I noticed it's lacking escaping the "." so it should be:
/^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/
Im rolling with
/^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3})+$/
and what about .info’s ?
oh shit… 3 years ago? :S
Well, this is just a rough check but not 100% accurate, for example this would be okay with john_doe.@gmail.com which is actually not a valid e-mail address (dot is not allowed as a last character in local part of e-mail).
Also it would accept john…doe@gmail.com which is also invalid since there cannot be more than one dot in a sequence.
These are just some flaws I noticed at the first sight.
My intention is not bashing just to point this out in case someone is planning to use this as a security check – not secure enough.
For info about valid e-mail addresses check this out: http://en.wikipedia.org/wiki/E-mail_address
Deepak,
Actually, I think you need to apply a escape for the dot (“.”). So , your function should be, instead:
function validateEmail(id)
{
var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$/;
return emailPattern.test(id);
}
Otherwise, the dot would mean “any character”. I believe such special characters need to be escaped.
Regards,
Federico
function validateEmail(fld) {
var error=””;
var tfld = trim(fld.value); // value of field with whitespace trimmed off
var emailFilter = /^[^@]+@[^@.]+.[^@]*ww$/ ;
var illegalChars= /[(),;:\”[]]/ ;
if (fld.value == “Enter your email Address”) {
error = “Please enter your Email address.n”;
} else if (!emailFilter.test(tfld)) { //test email for illegal characters
error = “Please enter a valid email address.n”;
} else if (fld.value.match(illegalChars)) {
error = “Please enter a valid email address.n”;
}
return error;
}
function validateEmail(fld) {
var error=””;
var tfld = trim(fld.value); // value of field with whitespace trimmed off
var emailFilter = /^[^@]+@[^@.]+.[^@]*ww$/ ;
var illegalChars= /[(),;:\”[]]/ ;
if (fld.value == “Enter your email Address”) {
error = “Please enter your Email address.n”;
} else if (!emailFilter.test(tfld)) { //test email for illegal characters
error = “Please enter a valid email address.n”;
} else if (fld.value.match(illegalChars)) {
error = “Please enter a valid email address.n”;
}
return error;
}
function validateEmail(fld) {
var error=””;
var tfld = trim(fld.value); // value of field with whitespace trimmed off
var emailFilter = /^[^@]+@[^@.]+.[^@]*ww$/ ;
var illegalChars= /[(),;:\”[]]/ ;
if (fld.value == “Enter your email Address”) {
error = “Please enter your Email address.n”;
} else if (!emailFilter.test(tfld)) { //test email for illegal characters
error = “Please enter a valid email address.n”;
} else if (fld.value.match(illegalChars)) {
error = “Please enter a valid email address.n”;
}
return error;
}
function validateEmail(fld) {
var error=””;
var tfld = trim(fld.value); // value of field with whitespace trimmed off
var emailFilter = /^[^@]+@[^@.]+.[^@]*ww$/ ;
var illegalChars= /[(),;:\”[]]/ ;
if (fld.value == “Enter your email Address”) {
error = “Please enter your Email address.n”;
} else if (!emailFilter.test(tfld)) { //test email for illegal characters
error = “Please enter a valid email address.n”;
} else if (fld.value.match(illegalChars)) {
error = “Please enter a valid email address.n”;
}
return error;
}
function trim(s)
{
return s.replace(/^s+|s+$/, ”);
}
function trim(s)
{
return s.replace(/^s+|s+$/, ”);
}
The ‘.focus’ is a function, it should be:
email.focus()
The ‘.focus’ is a function, it should be:
email.focus()
awesome
Works like gem.. Great use of reg expressions in javascript…
It´s a crack in the gem…
The address “mmm@mmm..com” will be accepted. But two dots together is not valid.
Fellas, use . It does not require any JS validation.
But only works with modern browsers. Unfortunately, the world hasn’t caught up just yet. —
Sent from Mailbox for iPhone