2

I have input name="email" and a button on the page.

How do I validate this input in live for a valid email address? And add some class for a button, class "active" if it is valid or "inactive".

This is a small task, so I don't want to use a plugins.

Thanks

Jasper
  • 5,090
  • 11
  • 34
  • 41
  • 1
    The fact that it is a small task is no reason not to use a well-tested plugin that will save you time. http://docs.jquery.com/Plugins/validation#Validate_forms_like_you.27ve_never_been_validating_before.21 – Chris Shouts Apr 25 '11 at 13:16
  • @Chris - using a plugin to validate a single field (that doesn't need validation anyway) doesn't make sense. @Steve - the best way to validate an email address is to send an email to it. Using a regular expression (or any other kind of parsing) is unreliable and not worth doing. – RobG Apr 25 '11 at 14:02
  • Using jQuery Validade plugin is very easy http://docs.jquery.com/Plugins/validation – msmafra Apr 25 '11 at 15:50

3 Answers3

7

I usually use this javascript function to validate in frontend:

function validateEmail(email) 
{ 
 var re = /^(([^<>()[\]\\.,;:\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,}))$/ 
 return email.match(re) 
}

it returns true or false. But anyway, you shouldn't usually only validate sensitive data in the frontend, but also on the server side.

tmaximini
  • 8,403
  • 6
  • 47
  • 69
2
$('#email').bind('keyup', function(){
    if(this.value.test([REGULAR_EXPRESSION])
        //doStuff -- add active class
    else
        //doOtherStuff -- add inactive class
});

replace [REGULAR_EXPRESSION] with one of the regular expressions found here: http://www.regular-expressions.info/email.html

Thor Jacobsen
  • 8,621
  • 2
  • 27
  • 26
  • Something like `var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;` – Dutchie432 Apr 25 '11 at 13:12
  • Unfortunatly most of the regular expressions you find for email are wrong. Top level domains aren't limited to four charachters. + is a valid charachter in an email address. – Wes Apr 25 '11 at 13:39
  • `this.value` will return a string, `test()` is a method of a RegExp, not of String so it should be `regExp.test(this.value)`. – RobG Apr 25 '11 at 14:00
0

i used this for mail validation javascript mail code

    function ValidateEmail(inputText)
    {
    var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
    if(inputText.value.match(mailformat))
    {
    document.form1.text1.focus();
    return true;
    }
    else
    {
    alert("You have entered an invalid email address!");
    document.form1.text1.focus();
    return false;
    }
  }
Ferrakkem Bhuiyan
  • 2,741
  • 2
  • 22
  • 38