Validate email address using JavaScript regular expression
Last month I wrote about regular expressions in Java, today I’ll show you how to use regular expression in JavaScript to validate email address.
Here is the code to validate email address in JavaScript using regular expression.
function validateEmail(elementValue){ var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; return emailPattern.test(elementValue); }
Explanation:
The argument to this method is the email address you want to validate.
In the method body we define a variable (’emailPattern’) and assign a regular expression to it.
/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/
To understand the regular expression we will divide it into smaller components:
/^[a-zA-Z0-9._-]+: Means that the email address must begin with alpha-numeric characters (both lowercase and uppercase characters are allowed). It may have periods,underscores and hyphens.
@: There must be a ‘@’ symbol after initial characters.
[a-zA-Z0-9.-]+: After the ‘@’ sign there must be some alpha-numeric characters. It can also contain period (‘.’) and and hyphens(‘-‘).
\.: After the second group of characters there must be a period (‘.’). This is to separate domain and subdomain names.
[a-zA-Z]{2,4}$/: Finally, the email address must end with two to four alphabets. Having a-z and A-Z means that both lowercase and uppercase letters are allowed.
{2,4} indicates the minimum and maximum number of characters. This will allow domain names with 2, 3 and 4 characters e.g.; us, tx, org, com, net, wxyz).
On the final line we call test method for our regular expression and pass the email address as input. If the input email address satisfies our regular expression, ‘test’ will return true otherwise it will return false. We return this value to the calling method.
You can call this method whenever you want to validate email address.
Bret
February 11, 2008 @ 1:10 pm
Hey, nice useful piece of code. Always nice to find something that takes a fairly common task, such as email validation, and breaks down the logic and provides a simple piece of code in the end.
Mastan Jhoni
February 14, 2008 @ 5:50 am
hey, nice explanation, its helped me allott.
More JavaScript Regular Expressions
February 20, 2008 @ 3:14 pm
[…] I wrote the JS regular expression article last week I had no idea that it will attract so many visitors. Not only did so many people read […]
Validate Zip code using JavaScript Regular expression
February 20, 2008 @ 10:04 pm
[…] to validate zip code using regular expression in JavaScript. Previously we talked about validating email and Social Security number using JS […]
Validate U.S Phone Numbers using JavaScript Regular expression.
February 28, 2008 @ 10:44 pm
[…] JavaScript regular expression to validate U.S phone number. Previously we talked about validating email , Social Security number and zip code using JS […]
Latha p
April 17, 2008 @ 12:52 am
Hi , email validation code present in this site is very nice and it is very useful to validate email address using regular expressions. My sincere thanks to the programmer who posted this. This help me alot.
Thanks & Regards,
Latha
Latha
April 21, 2008 @ 4:20 am
Hi can anyone help me how to invalidate the session , when i am clicking LOGOUT button. I use session.invalidate() method , the page has been expired. But when click back button on browser it goes to back page. How to avoid this. I request you any body can solve this problem.
yours
Latha
Swaroop
May 28, 2008 @ 1:23 am
Hi,
Very nice one which helped me a lot.
I tried the below code for checking alphabets, hyphen and underscore. However its not working.
Could any of you help me on this.
function validateChars(elementValue)
{
var charsPattern = /[a-zA-Z0-9_-]*/;
return charsPattern.test(elementValue);
}
Thanks.
Blaise Kal
June 5, 2008 @ 1:58 pm
Thanks for this. Saved me some work.
There is a small error in the regexp: top-level domains could be longer than 4 characters (like .travel and .museum).
J.Rajesh Joseph
June 19, 2008 @ 2:43 am
dfd
Mike VandeVelde
June 24, 2008 @ 2:46 pm
Don’t you need to escape the period? ie:
[a-zA-Z0-9._-]
should be:
[a-zA-Z0-9._-]
Otherwise, isn’t a period a single character wildcard?
And can’t a-zA-Z0-9 be replaced with \w?
ps Should also add apostrophe ‘ for Irish names, that’s the reason I was hunting this stuff down!
Josue
July 26, 2008 @ 7:58 am
Hi,
Thank you very much for this article. It helps me for achieving my form. In addition, your explanation is clear and light.
Dario
August 13, 2008 @ 5:36 am
Good Job – really easy to understand explanation
ray sweeten
August 19, 2008 @ 3:50 pm
Hey Mike,
[a-zA-Z0-9_] can be replaced with w.
also, because the . is included in the second character class(after @), this would be considered a valid email:
a@a…….com
not sure what the solution to that is. .
.{1} does limit the repetition of . to one, but since the previous characters have already been passed, the limiter becomes irrelevant.
anyone?
Armando
September 10, 2008 @ 5:53 am
Hi Zaheer,
Really clever solution, using regular expressions for validations.
I am studing at uni and we covered regular expressions on our
Unix system programing course. I see the usefulness of regular expressions now !
Keep posting more tips 😉
Cheers,
Armando
Matt
January 9, 2009 @ 4:44 pm
.@..ww
is a valid email address?
Rossati Giovanni
April 6, 2009 @ 2:05 am
thanks
Heartburn Home Remedy
April 15, 2009 @ 7:05 am
Not that I’m totally impressed, but this is more than I expected for when I found a link on SU telling that the info here is quite decent. Thanks.
Jim
May 15, 2009 @ 3:12 pm
Validate email address using regular expressions, nice piece of work. Very simple and clean. Thanks for the code. Helps me a lot.
— Jim
Gonzo
May 31, 2009 @ 9:47 am
This pattern isn’t a good for e-mail addresses. This pattern will filter out few of the WELL-FORMED e-mails and of MAL-FORMED as well.
mr disparate
June 17, 2009 @ 10:50 am
gonzo: that is quite an unfounded statement. could you please give examples of both. and if you are so smart, could you show solutions also? (there is already a comment showing it accepts faulty emails)
Martin
July 2, 2009 @ 2:37 pm
I too found that this regex has some flaws. An email like asdf@asdf would pass the filter. It doesn’t check for the .tld.
The guys at http://www.4guysfromrolla.com/webtech/052899-1.shtml have offered this, which ensures there’s a .tld :
^[\w-_.+]*[\w-_.]@([\w]+\.)+[\w]+[\w]$
I would encourage everyone to learn RegEx, it’s invaluable when you have to manipulate data, and who doesn’t these days. Zaheer’s lesson still teaches a lot.
@Mike VandeVelde
I believe apostrophes are illegal characters in emails.
Daniel
July 23, 2009 @ 10:11 am
based on the above I think that:
/^[w.+-]+@[w.-]+.[a-z]{2,6}$/i
might be a better solution.
w to match alphanumeric characters and underscores
i on the end to be case insensitive
{2,6} rather than {2,4} to cope with .museum
this still doesn’t address .@..ww or similar though.
/^((w++*-*)+.?)+@((w++*-*)+.?)*[w-]+.[a-z]{2,6}$/i
Should deal with that problem though (I have not tested this fully but it works on those that I have tested which it should work on and catches those that are invalid which I tried)
(w++*-*) matches an more than one alphanumeric followed by zero or more +s and zero or more -s
(w++*-*)+ matches this happening at least once.
((w++*-*)+.?)+ matches this happening at least once with or without a . afterwards
((w++*-*)+.?)* is the same except that it matches 0 or more times.
[w-]+ matches at least 1 alphanumeric character or hyphen.
I hope this helps people.
Chasalin
August 12, 2009 @ 3:24 am
Daniel wrote:
/^((w++*-*)+.?)+@((w++*-*)+.?)*[w-]+.[a-z]{2,6}$/i
Nice one!
I tested it with something like:
x test
x test..@..com
x test..@example..com
x test..@example.example.com
x test.2@example.com.
v test.2@example.example.com
(x fails, v passes)
I used to have a script of my own that worked really nice (apart from 6-char TLD), but was about 45 lines of code…
Zaheer and Daniel: Thank you for this huge improvement 😉
Banu Channakeshava
August 12, 2009 @ 8:04 am
In the above test.@test.com is pass, also numerics / _ are allowed to start the email address, below regex works fine to some extent.
/^[a-zA-Z]([a-zA-Z0-9-_])*(.[a-zA-Z0-9-_])*@[a-zA-Z0-9](([a-zA-Z0-9-_.])*)+.[a-zA-Z]{2,4}$/
Francisco Parada
September 21, 2009 @ 10:08 pm
Thanks and congratulations to Zaheer for this article: It is very well written and it is easy to read. Thanks also to the rest of people who contributed to enhance this code.
I would like to share with you the following regex that I tried with all samples shown before (and some more, of course). I think it is worth a try:
^([A-Za-z0-9]{1,}([-_.&’][A-Za-z0-9]{1,}){0,}){1,}@(([A-Za-z0-9]{1,}[-]{0,1}).){1,}[A-Za-z]{2,6}$
I think this pretty well matches a great number of e-mail addresses.
Regards,
Francisco.
Ajan
September 22, 2009 @ 5:57 am
Hai Latha,
I know its a very late reply for the question which you’ve asked. Anyway let it help the users who view this forum.
Your Question:
“Hi can anyone help me how to invalidate the session , when i am clicking LOGOUT button. I use session.invalidate() method , the page has been expired. But when click back button on browser it goes to back page. How to avoid this. I request you any body can solve this problem.”
Answer:
response.setHeader(“Cache-Control”,”no-cache,no-store”);
response.setDateHeader(“Expires”, 0);
response.setHeader(“Pragma”,”no-cache”);
just try to add the above code and check.
Madhu
November 4, 2009 @ 6:39 am
That helped me a lot!!
THANK YOU!!
ashish
November 23, 2009 @ 7:57 am
good one..!
Fabian
January 19, 2010 @ 11:11 am
Are mail-adresses with more than one “@” okay?
I was just wondering. Many of the regexp allow more than one “@”. Nevertheless some regexp allow combinations like test@test@example.org ….
Xin Seduction
March 23, 2010 @ 11:37 am
All exp failing at test:
test@example..org
Any solns for it ?
Bhushna
May 6, 2010 @ 3:46 am
Nice Post it will helps lot ,
How can we handle multiple email’s by using comma separated.
Bhushna
May 6, 2010 @ 3:50 am
any solution for (a@gmail.com,b@yahoo.co.in,c@gmail.com)
Bhushna
May 6, 2010 @ 4:01 am
Hi All,
am using this exp”” /^[a-zA-Z0-9._%-]+@[A-Z0-9.-]+.[A-Z]{2,4}(?:(?:[,][A-Z0-9._%-]+@[A-Z0-9.-]+))?$/i “”
it’s handling this format very fine a@gmail.com,b@yahoo.co.in , while come to a@gmail.com,b@yahoo.co.in,c@gmail.com not working.
plz help me for this req
Tom Walters
July 1, 2010 @ 7:18 am
This is just what I was looking for, thanks very much!
Dinesh
July 2, 2010 @ 1:04 am
Thanks. This RegEx pattern saved my day.
askkuber
July 7, 2010 @ 3:24 am
Thanks to u Very Good Explanation of Regular Expressions
askkuber.com TEam
KrayoN
July 26, 2010 @ 10:39 pm
@Bhushna for you : /^[a-zA-Z0-9._%-]+@[A-Z0-9.-]+.[a-zA-Z]{2,4}(?:(?:[,][a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+))?$/i
Mailpress 5.0 Email Validation Bug | Made of Everything You're Not | Eric Lamb
August 10, 2010 @ 9:59 pm
[…] Mailpress would throw an error on the second email which was pissing of my client’s client and my client (sigh…). The fix is pretty stratightford and easy; just replace the regular expression in Mailpress with the working one I cribbed from Zaheer. […]
Michael
September 2, 2010 @ 9:56 am
Actually if you read the relevant RFCs, pretty much any character is technically valid before the final ‘@’ sign (at least in escaped or quoted sections) – the format of that part is left completely to the receiving mail server to interpret (“Abc@def”@example.com is valid, for example). The part after the ‘@’ sign is more restrictive, because only certain characters can be used in domain names.
You should certainly support apostrophes before the ‘@’, all but one of these regexes suggested will fail on valid email addresses like
jim.o’neill@example.com
Mathew
September 29, 2010 @ 10:36 pm
Nice explanation.Now i really got the meaning of this regular expression.Untill now i was not known about the real meaning of this.This is nice and i thank you for the writter
vasantikabade
October 5, 2010 @ 10:31 pm
thanx. nice explanation.
Inspired
October 6, 2010 @ 8:26 am
Your expression does not validate Craigslist email addresses.
Sasho
November 11, 2010 @ 12:45 am
Great, thanks for this post. It is useful for me.
stryju
November 19, 2010 @ 10:05 am
/^[a-z0-9,!#$%&’*+/=?^_`{|}~-]+(.[a-z0-9,!#$%&’*+/=?^_`{|}~-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*.([a-z]{2,})/i
not the best one, but works
enam
November 27, 2010 @ 1:05 am
IT WORKS! THANKS THANKS THANKS.
Jimmy
December 5, 2010 @ 2:53 am
This helped me again as i forgot the regular expression and retrieved it from your site. Thanks a lot.
Sam
December 28, 2010 @ 4:19 pm
THANK YOU!!!
You have no idea how many websites I have gone through to find a simple explanation of this code so I may remake it without always copy-pasting just to get the job done.
You have helped a lot, thanks again.
nithya.k
December 29, 2010 @ 10:57 pm
That is nice .com it’s very useful for every one thansYou for giving this website
ZAHEERJAN
January 24, 2011 @ 11:15 am
HI FREND
Pnina
January 26, 2011 @ 3:51 am
I noticed that you do not allow for domains such as co.uk co.il and I am sure there are others. you might want to revise…….. but thank anyway
Zenonline
January 30, 2011 @ 3:52 pm
@Pnina, the code will work fine on co.uk domains as the regex check after the “@” sign allows multiple periods (“.”) to be there (this allows for subdomains to be allowed as well) so as long as the last set of digits after the period are 2-4 digits long the validation will work
ruby
February 1, 2011 @ 2:09 pm
It allows Testyahoo@yahoo..om , if we type two dots , it is validating as true.
Rca Ieftin
February 18, 2011 @ 6:27 am
I didn’t know that you can validate the email address using JavaScript regular expression. I suppose it’s the best option if you need to validate in a easiest way this task.
ifti
March 16, 2011 @ 3:23 am
its not working n its allow String “r@#$” if i take only “[a-zA-Z0-9._-]+” as a patten;
expert
March 20, 2011 @ 6:40 am
this one won’t work with a+b@g.com, right?
Spiderman
May 4, 2011 @ 12:49 pm
Use this regex instead
/^((([a-z]|d|[!#$%&’*+-/=?^_`{|}~]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])+(.([a-z]|d|[!#$%&’*+-/=?^_`{|}~]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])+)*)|((x22)((((x20|x09)*(x0dx0a))?(x20|x09)+)?(([x01-x08x0bx0cx0e-x1fx7f]|x21|[x23-x5b]|[x5d-x7e]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])|(\([x01-x09x0bx0cx0d-x7f]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF]))))*(((x20|x09)*(x0dx0a))?(x20|x09)+)?(x22)))@((([a-z]|d|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])|(([a-z]|d|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])([a-z]|d|-|.|_|~|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])*([a-z]|d|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF]))).)+(([a-z]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])|(([a-z]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])([a-z]|d|-|.|_|~|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])*([a-z]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF]))).?$/
Confused
May 24, 2011 @ 4:20 am
This just returns the value of the email you pass it? It dosen’t result in a true/false test? How is this of any use?
Meserias
May 24, 2011 @ 8:19 am
ATENTION: this regex has a bug. The right syntax is:
/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+[.]{1}[a-zA-Z]{2,4}$/
Without this modification a string like name@yahoo is a valid emalil address.
for Confused: this function return true if the user type a valid email address (name@domain.extension) and false if not.
You can call the function in this way:
var valid_email=validateEmail(document.getElementById[‘field_id’].value);
if(valid_email){ [your code] }else{ [your code] }
This validation is for you users, but you must do another validation on server side when you save your data.
Mudassar Mumtaz
June 4, 2011 @ 12:09 pm
these are easy expressions to understand and aplliying…really i like it a very much.
Deepak Agg
June 9, 2011 @ 6:52 am
function val()
{
var email = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+[.]{1}[a-zA-Z]{2,4}$/;
}
if(document.f.t3.value.search(email)==-1)
{
alert (“plz enter tha email”);
return false;
}
Email
Tank
June 17, 2011 @ 9:15 am
I modified this a bit to allow sub domains, multiple tld’s and removed validating multiple .’s (user@domain..com)
(^[a-zA-Z0-9._-]+@[a-zA-Z0-9]+([.-]?[a-zA-Z0-9]+)?([.]{1}[a-zA-Z]{2,4}){1,4}$)
will validate abc@domain.co.uk, abc@domain.com.tw, abc@sub.domain.co.uk
wew
July 13, 2011 @ 1:28 am
wewrer
Jasmine
July 19, 2011 @ 4:19 am
This email validation script is awesome, although I replaced it with Meserias’ modification. Thanks for the script!
Maddie
August 3, 2011 @ 12:58 pm
Actually Maserias’ modification works really well except that it accepts abc@.xyz.com. “@.” shouldn’t be together. I made a minor modification to it:
/^[a-zA-Z0-9._-]+@[a-zA-Z0-9][a-zA-Z0-9.-]+[.]{1}[a-zA-Z]{2,4}$/
So this checks to see that the domain starts with alphanumeric characters. The credit however goes to Meserias!
mahesh
August 6, 2011 @ 1:00 pm
gr8….easy to understand and implement
John K
August 13, 2011 @ 6:12 pm
Maddie’s regular expression doesn’t recognize a@b.com (exactly one character between ‘@’ and ‘.’. This modification corrects this problem:
/^[a-zA-Z0-9._-]+@[a-zA-Z0-9][a-zA-Z0-9.-]*[.]{1}[a-zA-Z]{2,4}$/
Jerry
August 21, 2011 @ 6:33 pm
It’s a pet peeve of mine that people publish regular expressions for email addresses when they simply don’t know the standard. Every single regular expression on this page, article and comments alike, fails to validate email addresses of the form joe+list@domain.com (though to be honest I didn’t check all the older comments). People grab these expressions and throw them into their code, thinking that will make them fit some sort of standard, when they don’t.
The inability to add the +suffix to an email address undermines the usefulness of the feature even where it is accepted. PLEASE add proper support for the standard and spread the word.
There’s a good article at http://www.regular-expressions.info/email.html that discusses tradeoffs of various regular expressions for validating email addresses.
On this form I’m using a + sign in my email address.
khaiknievel
August 26, 2011 @ 2:14 am
use this . from jquery.validate.js => no, its not, the longer the better. this just works
/^((([a-z]|d|[!#$%&’*+-/=?^_`{|}~]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])+(.([a-z]|d|[!#$%&’*+-/=?^_`{|}~]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])+)*)|((x22)((((x20|x09)*(x0dx0a))?(x20|x09)+)?(([x01-x08x0bx0cx0e-x1fx7f]|x21|[x23-x5b]|[x5d-x7e]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])|(\([x01-x09x0bx0cx0d-x7f]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF]))))*(((x20|x09)*(x0dx0a))?(x20|x09)+)?(x22)))@((([a-z]|d|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])|(([a-z]|d|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])([a-z]|d|-|.|_|~|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])*([a-z]|d|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF]))).)+(([a-z]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])|(([a-z]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])([a-z]|d|-|.|_|~|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])*([a-z]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF]))).?$/
DisFanJen
September 3, 2011 @ 6:50 am
Thanks this is a simple and elegant solution to the problem.
Also thanks to Tank. I found his modification to the expression to be the best for my needs. 🙂
kumar
September 8, 2011 @ 11:11 pm
not bad
iftikhar
September 21, 2011 @ 10:25 pm
thanx i got alot from this
sampath
October 3, 2011 @ 12:50 am
I used this expression and worked well.
/(^[a-z0-9!#$%&’*+/=?^_`{|}~-]+(.[a-z0-9!#$%&’*+/=?^_`{|}~-]+)*|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|\[x01-x09x0bx0cx0e-x7f])*”)(.)?@(([a-z0-9]([a-z0-9-]*[a-z0-9])?.)+[a-z]{2,}|(((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)))$/i
As a Java String
“(^[a-z0-9!#$%&’*+/=?^_`{|}~-]+(\.[a-z0-9!#$%&’*+/=?^_`{|}~-]+)*|”(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*”)(\.)?@(([a-z0-9]([a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,}|(((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)))$”
Of-course the length part of the email is not considered in the regular expression.
This will allow ! # $ % & ‘ * + – / = ? ^ _ ` { | } ~ in the local part and the local part can end with dot (.)
domain part can be IP or domain
ibna
October 3, 2011 @ 8:14 am
greetings ..
i just want to know does this regex check dot at the beginning of email id because as per the expression we can have dot and digits at the start as well like for example:
.abc@yahoo.com
77def@fgt.com
Are these id’s valid?? please brief on that ..
Thankyou
Joby Chacko
October 28, 2011 @ 5:00 am
fantastic!!!!!!!. Thanks for this simple solution.
henru
November 8, 2011 @ 6:14 am
how can we make the expression for a specific mail like gmail
z666zz666z
November 17, 2011 @ 8:24 am
To end on “@gmail.com” just use this as final part:
/@gamil.com$/
If want to check anything before @ add checks at begining.
This one will only allow leters, numbers and ‘_’ and ‘-‘ as left part of @ and must be on gmail.com
/^[0-9A-Za-z_-]+@gamil.com$/
An this other one is also to accept dot on user part, but not at start neither near the @:
/^[0-9A-Za-z_-]([.][0-9A-Za-z_-]+)*@gamil.com$/
Hope helps!
rabia
November 23, 2011 @ 7:22 am
good 🙂
hak
November 24, 2011 @ 2:59 am
what if someone inputs ‘joe@support.com.com’
or @.edu.edu
??
Multiple email
December 13, 2011 @ 5:29 am
This RegEx allows multiple email addresses if it is separated by a “;”
In a textbox if i need to validate a single email address and if two addresses are entered then this RegEx wont work.
Mardi
December 15, 2011 @ 3:19 am
Hi
I am VERY new too Javascript and need to validate a form for a tafe assignment. So far I have added code to validate required text fields and a drop down menu and have all the error messages come up in the one alert box. Now I am having trouble figuring out how to add the code to validate an email and have the error message appear in the same alert box as they are other fields are being validated. I hope I am making sense!!
If anyone is able to help this is my code! Please ignore all the comments! I have to add them as parrt of the assignment
function checkforblank() {
var errormessage = “”;
if (document.getElementById(‘selectmenu’).value == “”) {
/* the getElementById is determined by the id given in the below html.
For example: */
errormessage += “Please specify your title n n”;
document.getElementById (‘selectmenu’).style.borderColor = “red”;
/* .style.borderColor highlights the borders of the text fields in red when there is an error */
}
if (document.getElementById(‘fname’).value == “”) {
errormessage += “Please enter your first name n n”;
/* error message if first name field is not filled out */
document.getElementById (‘fname’).style.borderColor = “red”;
}
if (document.getElementById(‘lname’).value == “”) {
errormessage += “Please enter your last name n n”;
/* error message if last name field is not filled out */
document.getElementById (‘lname’).style.borderColor = “red”;
}
if (document.getElementById(‘enquiry’).value == “”) {
errormessage += “Please submit an enquiry n n”;
/* error message if viewer does not enter an enquiry */
document.getElementById (‘enquiry’).style.borderColor = “red”;
}
if (errormessage != “”) {
alert (errormessage);
/* alert (errormessage) displays the specified error messages that were created in the
above if statements */
return false;
}
/* return false stops the form from being submitted to the server */
// End of function
}
Jeremy Johnstone
December 16, 2011 @ 11:31 am
This regex has so many flaws I have to heavily recommend everyone ignore it. Worse than the numerous false positives others have already pointed out, it also regexs common perfectly valid email addresses. For example, the + character is very valid and not super uncommon in the left hand side of an email address.
Buyer beware, you get what you pay for when you use this regex!
John K
December 31, 2011 @ 2:29 pm
here’s the regex modified to accept + signs after the first character of the address:
/^[a-z0-9._-][a-z0-9._-+]*@[a-z0-9][a-z0-9.-]*[.]{1}[a-z]{2,4}$/i
I also shortened it by adding i modifier at end, so don’t need to specify A-Z for uppercase letters. The regex still has false positives, no doubt, but no false negatives for + signs.
Rashid
January 22, 2012 @ 1:57 am
ya zaheer paratha koon ha?????
Tory
January 24, 2012 @ 12:13 pm
The solution Tank gave seems to pass all my tests and it’s a one liner. Thanks Tank
Kent
February 2, 2012 @ 3:27 pm
Does Tank’s address a+anything@gmail.com? It did not seem too. Jerry mentioned this.
This is a feature at gmail, add a “+(anything you pick)” before the @ on your regular gmail address, and the email will still be delivered to you, but you can send it to special filters.
Modifying Tanks to this
/^[a-zA-Z0-9._+-]+@[a-zA-Z0-9]+([.-]?[a-zA-Z0-9]+)?([.]{1}[a-zA-Z]{2,4}){1,4}$/;
Seemed to work.
dinus
February 8, 2012 @ 9:09 am
Hi,
can some one please explain the meaning of below regular expression :
“^([0-9a-zA-Z]([-\.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$”;
thanks in advance
Neelaka
February 13, 2012 @ 10:56 pm
thank you for helping to validate e-mail
ram
February 14, 2012 @ 7:42 am
elseif($_POST[‘name’]==eregi(‘^[a-zA-Z ]+$’)) is correct
ganesh123
February 14, 2012 @ 7:44 am
error in eregi(‘^[a-zA-Z ]+$’))
daisy
February 27, 2012 @ 1:19 am
Hi
I want upload pdf book from any location in the PC to specific folder and save this path in mysql. With possibility of download this book.And when I want delete this PDf from the sit this PDf also delete from the folder and its path from the mysql .Please help me.
Venu
March 2, 2012 @ 1:17 am
Hi I need a code.I have ONE text box.When i am filling the text box,First letter should be alphanumeric and last 4 should be numbers.Give me replay ASAP.
compzets
March 3, 2012 @ 3:23 am
gud post buddy
Alito
March 3, 2012 @ 5:32 pm
Very helpful!
Lightning
March 30, 2012 @ 6:30 am
try
/([w-.]+)@((?:[w]+.)+)([a-z]{2,4})/gi
Abdul Wahab Qambrani
April 3, 2012 @ 9:28 am
Asslam-u-Alaikum,
Very Informative and Helpful code. specially learners and beginners.
Wasalam
Andrea
April 9, 2012 @ 12:41 am
Thanks everyone for your contributions.
I went with Tank’s solution and Kent’s modification. Does the trick for me!~
Mohamed Alaa
April 9, 2012 @ 1:24 pm
I’m using this and it’s working perfect:
mailRegex = /[a-z0-9!#$%&’*+/=?^_`{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])/;
This will help you validating wrong emails including: name@sample..com
Best Regards,
Mohamed
Darryl Young
April 17, 2012 @ 8:38 am
Hey,
I’m glad I came across this thread and I hope I can get some help off you guys! I’m trying to work with an previously written JavaScript function to validate an email but it’s having problems if the user enters a space at the end of their email address (it happens, especially on mobile with auto-complete etc). How could I amend the following code to allow a space at the end?
function checkMail(emailInput) {
filter = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$/;
if(!filter.test(document.lpform.email.value)) {
$(“#email”).addClass(“error”).focus();
$(“#email”).blur();
document.getElementById(‘dataStatus’).style.display=”block”;
return false; }
return true;
}
Thanks so much! I really appreciate it. =D
Darryl Young
April 19, 2012 @ 4:56 am
Ok, I just added s and that worked…
filter = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+.[a-zA-Zs]{2,4}$/;
Thanks anyway.
John
May 1, 2012 @ 8:19 am
Hello All,
I am Glad that i have landed to this email. I have a new requirement for validating email for a new format, can anyone tell me how to by pass.
Contact350test/Vendor@ab.com
I tried removing / from the below exemplist, But the code is throwing JS error.
var exemplist =/^[a-zA-Z][w.-]*[a-zA-Z0-9]*@[a-zA-Z0-9][w.-]*[a-zA-Z0-9]*.[a-zA-Z][a-zA-Z.]*[a-zA-Z]$/
Thanks in advance.
jagadeesh
May 14, 2012 @ 9:32 am
very nice content it is very useful to me.
naveen
May 25, 2012 @ 1:03 am
fgsdf gsdfg
naveen
May 25, 2012 @ 1:05 am
cvcvbcvb cv b
Lúcia Ribeiro
June 19, 2012 @ 11:55 pm
I neead to receio my email
Lúcia Ribeiro
June 19, 2012 @ 11:57 pm
I
Med.
Lúcia Ribeiro
June 19, 2012 @ 11:59 pm
Thanks
Lúcia Ribeiro
June 20, 2012 @ 12:00 am
I breaste
Meesam Akhtar
July 4, 2012 @ 1:24 am
Valid email-id for all different kinds of email-ids(e.g. meesam.akhtar@domain.com OR meesam.akhtar@domain.co.in OR meesam.akhtar@domain.travel.uk.
Regular expression for Email-Id– /^([a-zA-Z0-9_-])+@(([a-zA-Z0-9-])+)+(.[a-zA-Z]{2,6})(.[a-zA-Z]{2})?$/i
Dennis
July 16, 2012 @ 1:32 am
@John I hope i’m not too late to answer you. Try this
/^(([a-zA-Z0-9._-])||([a-zA-Z0-9._-]+/))+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$/
to bypass this Contact350test/Vendor@ab.com.
ramesh
July 17, 2012 @ 5:19 am
very nice..easy to learn or do…
Mathijs
September 18, 2012 @ 2:11 pm
Pity that this does not take account with emails like initials.lastname@student.college.com
sneha
October 11, 2012 @ 6:05 am
Great dude 😀 we were looking for the regular expressions explanation since long. 😀 Thanx a ton
karim
April 22, 2013 @ 1:47 am
this is gud
Jeff Robert Dagala
April 29, 2013 @ 7:06 am
Thank you for your regexp, it really works!
Eduardo Neto
October 31, 2013 @ 5:09 pm
thank you guy!
solar lights
February 18, 2014 @ 4:40 pm
Even g?ing ove? budget sl?ghtly to get the sttyle
of lights t??t ?ou want caan leave you feeling l?ke the projected wasn’t completed as t?ough you wanteed ?t.
The se?ond reasons w?y solar Christmas lights
shoul? ?? u?ed is t?at t?ey are rel?tively safer than th? traditional
Christmas lights. Youu ?ill ?? cleaning t?em ?uring the day ?o thdre i? no need for them to b? on and
you don’t ?ant to damage the lights or electrocute yoursekf ?n the
process.
car insurance New Zealand
February 18, 2014 @ 5:00 pm
As has been stated, medical insurance is a thing that could be a very serious matter.
Usually, PPOs cost more than traditional HMOs,but offer more options
to their members. The majority off people invest in companies that provide cheap
insurance quotes.
?????????????
February 18, 2014 @ 9:59 pm
Greate pieces. Keep writing such kind of info on your
blog. Im really impressed by your site.
Hello there, You have performed an excellent job.
I will certainly digg it and for my part recommend to my friends.
I am confident they’ll be benefited from this web site.
final fantasy vi android download
February 18, 2014 @ 10:37 pm
Asde from video games, the event also focuses on anime and manga products.
If you’re reading this article, it means you’re interested in
downloading soime free Android games- start with tthis
one. The clitoris’ shape actully resembles the penis, except for its body is not outside
but insdide unnder the so-called hood.
Psn Code
February 19, 2014 @ 12:41 am
Wow, that’s what I was seeking for, what a information!
present here at this webpage, thanks admin of this
web site.
Visit my site; Psn Code
arrassylofs
February 19, 2014 @ 6:31 am
how much does a mental health counselor make [url=http://www.rgdmape.com/fiere/cytotec.html]cytotec[/url] mercy general health partners
hungry shark evolution hack
February 19, 2014 @ 7:38 am
Incredible! This blog looks just like my old one!
It’s on a totally different subject but it has pretty
much the same layout and design. Outstanding choice of colors!
Also visit my web-site :: hungry shark evolution hack
wizard101 crown Generator
February 19, 2014 @ 10:05 am
I’m not sure why but this blog is loading incredibly slow for
me. Is anyone else having this issue or is it a issue on my end?
I’ll check back later on and see if the problem
still exists.
Also visit my web site: wizard101 crown Generator
spiffyaccountan29.jigsy.com
May 30, 2014 @ 7:22 pm
Hurrah, that’s what I was seeking for, wht a material!
existing here at this webpage, thanks admin of this webb site.
www.teamiseti.org
June 10, 2014 @ 5:17 am
You should nevertheless forever be all aware of the fact
that utilising a rifle is a large obligation and thast it shoulld in no situation be
used for the wrong things, neither aginst family nor against animate beings or lesser
beings. This “A Christmas Story” quote is a narration from older Ralphie.
The very first medal India received at the Olympic Games came
from Gagan Narang, a shooter who won the bronze medal, also known as the third prize, in the men’s 10 m aiir rifle event.
magnapress
June 10, 2014 @ 10:32 pm
Thanks for some other excellent post. The place else may just anyone get that kind of information in such an ideal
means of writing? I have a presentation next week, and I’m on the look for such
information.
scrap car Bishops Stortford
June 14, 2014 @ 2:48 pm
I enjoy what you guys are usually up too. This sort of clever
work and reporting! Keep up the superb works guys I’ve incorporated you guys to our blogroll.
http://Draconianicon5332.tumblr.com/
June 14, 2014 @ 8:12 pm
I write a comment when I appreciate a article on a site or if I have
something to valuable to contribute to the discussion. Usually it
is a result of the passion communicated in the article I browsed.
And after this article Validate email address using JavaScript regular expression. I was actually excited enough to
leave a thought 🙂 I do have 2 questions for you if you usually do not
mind. Is it just me or does it appear like a few of these remarks come across
as if they are written by brain dead folks? 😛 And, if you
are posting at other sites, I’d like to keep up with everything new you have to post.
Would you list every one of your community pages like your Facebook page, twitter feed,
or linkedin profile?
nxy.in
June 27, 2014 @ 5:03 am
Soon the drugs you use are not enough and you need more
and more. Get auto insurance quotes [nxy.in] for low income and
you will find that there are policies in the market that
have low rates. A rising number of countries in the world today have
made it compulsory for an automobile to be insured at the time of
purchase.
Wilbert
August 31, 2014 @ 1:05 am
What’s up i am kavin, its my first occasion to commenting anywhere,
when i read this paragraph i thought i could also make comment due to this good
piece of writing.
fake traffic tool
September 8, 2014 @ 3:24 am
With havin so much written content do you ever run into any issues of plagorism or copyright infringement?
My website has a lot of completely unique content I’ve
either authored myself or outsourced but it looks like a
lot of it is popping it up all over the internet
without my authorization. Do you know any methods
to help prevent content from being ripped off? I’d definitely
appreciate it.
danlynch.org
October 13, 2014 @ 5:28 am
Had been actually searching for just an average shower enclosures before
I uncovered this site, did not have any idea there were such
a thing as a ‘steam shower enclosure’, really, might possibly just may have to have one
Feel free to visit my homepage; steam sauna shower
units [danlynch.org]
author
December 1, 2014 @ 1:17 am
Most protein shakes are loaded with sugar, fat, and other ingredients that
aren’t even necessary for the body. If you want
to build a considerable business, you’ll have to be able to come up with constant leads.
7 million which was up $ 110 million compared to the year previous.
promotional item
December 26, 2014 @ 3:43 am
Very rapidly this web page will be famous among all blogging and site-building people, due to it’s
good articles oor reviews
hack livejasmin
March 16, 2015 @ 9:26 am
If this is important to you, make sure that the web video hosting service you choose to use offers these features.
There are three different messages that can be chosen for St.
” Hopefully and follow-up interviews can get the public’s opinion.
ERTERT
March 24, 2015 @ 9:08 am
VERY HELPFUL
pirate kings apk mod money
July 13, 2015 @ 2:40 am
For case in point, exercise routines like push-ups do the job the triceps,
biceps, chest, back, shoulders and even the abs which provides you a plethora of muscle mass targets to
do the job on. Persistence is key. The basic nature of this festival is totally commercial
and usually experience mass attendance with great pomp and show.
Satyapriy
September 8, 2015 @ 12:26 pm
Very much useful… Lot many thanks…
Keep helping…
『激安人気』【最大800円OFFクーポン配布】レビューキャンペーン送料無料
November 15, 2015 @ 8:46 am
クールな情報の仕事を維持します!ありがとうは、巨大なポストを
【あす楽対応】ムーヴフィットジュニアS SW(フロストグレー/FG/10869) コンビ
November 23, 2015 @ 9:35 pm
クサノオウのエリート主義のシャッフルボードheadaのjhelisaはaukinのtrubus義務
Streaming Hentai Online Free
January 15, 2016 @ 11:17 pm
It’s an remarkable post designed for all the online people; they will obtain advantage from it I am sure.
Alex Meraz
February 8, 2016 @ 12:23 pm
Hola
care2.com
February 10, 2016 @ 7:03 am
On the subject of digital advertising training, some firms are unique in it.
Other instructional institutes, with a purpose to sustain and supply
increasingly more online courses, have created quite a few training applications in the space of digital advertising and marketing.
Kevin Hansen
September 23, 2016 @ 3:09 am
Have to do an Contactformular validation and this really helps me out to understand the syntax of the RegExp() pattern! Well done Sir!
sangy
October 25, 2016 @ 4:36 pm
Very well explained, good job! It helped me with my home work to understand regular expression for the email. Thank you!
darigh
March 25, 2017 @ 6:44 am
Here is the most recent validation regex witch accepts new DNS domain name extension with more than 3 characters (like: domainname.brussels ) in Javascript:
/^([^()[]\.,;:s@”]+(.[^()[]\.,;:s@”]+)*)@(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,})$/
example
April 24, 2017 @ 12:58 pm
This design is wicked! You obviously know how to keep a reader amused.
Between your wit and your videos, I was almost moved to start my own blog (well,
almost…HaHa!) Wonderful job. I really loved what you
had to say, and more than that, how you presented it.
Too cool!
Nifemi
May 4, 2017 @ 11:06 pm
Very helpful. Thanks a lot for the article
94Clifford
August 2, 2017 @ 10:08 pm
Hello admin, i must say you have high quality articles
here. Your blog should go viral. You need initial traffic boost only.
How to get it? Search for: Mertiso’s tips go viral
St John
September 10, 2017 @ 9:29 am
no full cover because you can add multiple subdomaines like hello@domain.fr.net.com.hello.blab
:'(