A how to guide – Live Email Validation

Just Posted: Twitter ‘Approving’ Apps for access to xAuth

In this tutorial I will describe how you can validate the format of an email address “live” using jQuery and regular expressions without the need for a plugin (See Demo). The code is pretty lightweight, uses a simple jQuery event to fire the code, and gives the user great visual feedback on whether what they’ve entered is good, or bad… so here we go

validatescreen

HTML

First up, let’s create the HTML:

<div><input type="text" id="validate" width="30"><span id="validEmail"></span></div>

This creates a basic input text box for the email address, and a location for an image to appear for user feedback. Pretty simple.

Javascript

Next, let’s create the function that checks the email address against a regular expression. This expression may not be perfect, but it does a pretty good job:

function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
return pattern.test(emailAddress);
}

Stylesheet

For this example, I am lumping everything into one .html page – you probably want to create your own seperate stylesheets, and .js files – but for the purpose of this demo, let’s stick with it in one:

<style>
#validEmail
{
margin-top: 4px;
margin-left: 9px;
position: absolute;
width: 16px;
height: 16px;
}
</style>

jQuery

The last part to this is obviously the jQuery to do the live validation. It’s pretty simple, we hook up a keyup event to the input box we created in the HTML section. Within that event function, the jQuery calls the isValidEmailAddress function with the current value of the input box. If it returns a positive result (ie the email address is valid) then it will show a nice validyes icon. If not, it will display an validno icon. Lastly, it also hides the tick/cross images when the input box is cleared.

$(document).ready(function() {

$("#validate").keyup(function(){
var email = $("#validate").val();

if(email != 0)
{
if(isValidEmailAddress(email))
{

$("#validEmail").css({ "background-image": "url('validYes.png')" });

} else {

$("#validEmail").css({ "background-image": "url('validNo.png')" });

}

} else {

$("#validEmail").css({ "background-image": "none" });

}
});
});

This should obviously be placed into the <HEAD> section of your page, after you have declared the jQuery library.

Finish

That’s it… putting this altogether you will have a nice live email validation input box which will validate against a regular expression.

Demo

You can view a demonstration of this tutorial in action here.

Download

Download

Thanks for checking out this brief tutorial on live email validation with jQuery and regular expressions. Click the icon on the left to download the sourcecode, and let me know how you get on in the comments section below… Good luck!

Tools to help you learn…

Learning jQuery 1.3

Learning jQuery 1.3

Amazon Kindle 2

Amazon Kindle 2

jQuery UI 1.6

jQuery UI 1.6

35 Responses to “A how to guide – Live Email Validation”

  1. Clueless with regex. What would I need to do to allow the “+” modifier to allowed characters in an address like info+errors@jobsearchlog.com

  2. Gabe says:

    Love it, nice work, thanks for the useful example!

  3. Chris says:

    It’s nice to explain the concept of live validation, but I think you should have a warning not to use this actual code in production, before it spreads all over the net. It doesn’t accept perfectly valid e-mail addresses like *@qz.to and fred&barney@stonehenge.com. Apart from checking for an @ symbol somewhere (to catch the three people left who think their AOL screen name is an e-mail address) and maybe a dot, there’s no good reason to attempt to “validate” e-mail addresses. And it’s almost guaranteed that anyone who tries will get it wrong.

  4. dan says:

    just say in a tool tip or next to the email field
    “we will use this email address to send you the login data”

    and you won’t need email validation :D

  5. Steve Reynolds says:

    yepp definitely – this was meant to be more of a concept on how to do live validation with jQuery and regular expressions rather than email specifically. I did mention that the regexp is never perfect, and it doesnt validate that its an actual working email address either – just checks the loose format.

    Still think its a valid example though of how to implement… Thanks for the feedback.

  6. Jan Jarfalk says:

    Using regular expressions for form validation is really good, but not always enough. To suite my needs I built my own Jquery input plugin it uses both regular expressions, ajax requests and custom javascript functions.

    The plugin is more of a plugin and therefor a bit more heavy and the documentation isnt as complete as this one but it should be farily easy to implement anyhow.

    http://www.unwrongest.com/projects/valid8

  7. Nice and really well-organized article (you love web 2.0, i know!).

    Regarding the regular expression, we can find the one that meets our requirement, so this should not be an issue. But one thing I could not stop saying is that “live validation of email” would praise developers seek into the code if it was going to really validate the email “live”. I mean whether the email really exists in this world! This one has hit my mind, perhaps this would come live.

    In one of the comments above we have dan say:
    “just say in a tool tip or next to the email field
    “we will use this email address to send you the login data”

    and you won’t need email validation ”

    Doesn’t this mean that live validation is a requirement (not that serious!)?

    Thanks a lot.

  8. Nick Tulett says:

    Nice example but avoid giving advice like “This should obviously be placed into the section of your page, after you have declared the jQuery library.” For performance reasons, placing JS in the HEAD should be a last resort.

  9. Steve Reynolds says:

    Really? Well that is new to me… thanks!

  10. Mike says:

    How would you go about adding a link to the tick image? It would be good to have a send button that only appears once a valid email is entered…

  11. Power Man says:

    Hi Steve,

    Im trying to implement your tutorial into my existing form happily named txtEmail.

    I changed the parameters from #validate to textEmail but it doesn’t work, my paths and connections are correct, any ideas

    power man
    Awesome tut, you should sell your knowledge.

  12. Stefan Jancar says:

    Hello, it was great help for me… thanx.

  13. anony says:

    thanks was helpful!!! :)

  14. Thanks man, saved me some major time.

    I’m incorporating this into my next web app

  15. Penton says:

    This script is so cool. I used your isValidEmailAddress at 2 sites now. Need to tweak the regxp to accomodate some special characters. But, in general, your regexp is pretty sufficient.

  16. Jani-Matti Hätinen says:

    The above regexp also doesn’t accept UTF-8 characters in either the first (local) part or the domain part. Both of which are completely valid in an e-mail address.

    A more correct (but still probably not perfect) e-mail validation would check the following things:
    – total length of the address is up to 254 characters of which the first (local) part
    is up to 64
    – in the local part, inside quotation marks (“”) everything goes, so no
    validation of any kind there. however outside of that:
    – no whitespace anywhere
    – one, and only one @ character
    – none of these characters in either part ()[]\;:,
    – none of these characters in the domain part “!#$%&’*+/=?^_`{|}~ (to be
    precise there should be no other punctuation marks except dot and hyphen
    (.-))
    – in the domain part no dot is immediately preceded by a hyphen
    – the domain part includes at least one dot (.)
    – dot (.) is not the last character of either the local or domain part
    – there are no double dots (..)

    Needless to say, trying to encompass all of the above in a single regexp would be rather pointless. Instead, the sane way to do e-mail address validation is to first check the common errors and then to split the address into at least the local and domain parts (and the local part further into inside quotes and outside quotes parts) and check each of those individually.

  17. Jani-Matti Hätinen says:

    Sorry this:
    - in the domain part no dot is immediately preceded by a hyphen

    Should be:
    - the domain part does not start nor end with a hyphen
    - in the domain part no dot is immediately preceded or succeeded by a hyphen

  18. Jay says:

    Hi,
    Your tool is cool. Thanks a lot! I am using it in a few web based products of my own.
    Jay Pagnis

  19. KonKxy says:

    Thanks, good tutorial.

  20. psjandhyala says:

    Thanks , it is very good tutorial, i included this concept in my project and it is working great

  21. ken says:

    hehe, exactly what I was looking for :) Bunch of thanks!

    @dan great catch. However, sometimes is about misspelling and a “on-fly” validation like this can help :)

  22. vishnu says:

    Love it, nice work, thanks for the useful example!

  23. azamhafis@yahoo.com.my says:

    Live Email Validation with Query

  24. Emo Cutie is the best emo blog on earth!

  25. Rueben says:

    A family reunion is an effective form of birth control

  26. sanchy says:

    awesome, thanks!

  27. Wouter van den Brink says:

    While trying out and using in a different way the code form your usefull and nice howto: In the third code panel above, in the phrase “if(email != 0)” on line 06: would it not be better to say “if(email != ””)”, empty string instead of zero. I noticed that userinput of only “0″ was not evaluated, changing it to the empty string removed my problem

  28. I so enjoyed every bit of this site and I’ve bookmarked your blog to keep up with the new topics you will post in the future.

  29. sagivo says:

    thanks!
    simple and helpful article!!
    :)

  30. Zoe Freimark says:

    appreciated this blog!

Trackbacks/Pingbacks

  1. [...] Live Email Validation with jQuery | Steve Reynolds Blog [...]

  2. [...] A how to guide – Live Email Validation | Steve Reynolds Blog (tags: jquery email validation) « links for 2009-03-04 [...]

  3. [...] bookmarks tagged email A how to guide – Live Email Validation | Steve Rey… saved by 5 others     musikl bookmarked on 03/07/09 | [...]

Leave a Reply