views:

622

answers:

6

For the love of God I am not getting this easy code to work! It is always alerting out "null" which means that the string does not match the expression.

var pattern = "^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$"; 

function isEmailAddress(str) {

    str = "[email protected]";      

    alert(str.match(pattern)); 
    return str.match(pattern);    

}
+3  A: 

If you define your regular expression as a string then all backslashes need to be escaped, so instead of '\w' you should have '\\w'.

Alternatively, define it as a regular expression:

var pattern = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;


BTW, please don't validate email addresses on the client-side. Your regular expression is way too simple to pass for a solid implementation anyway.

See the real thing here: http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html

J-P
This regular expression doesn't support addresses like [email protected]
Nadia Alramli
Thanks a lot for your help!
azamsharp
This is not for any production application. This is for a small demo I am creating. Thanks for pointing that out though!
azamsharp
it doesn't support emails like [email protected]
Space Cracker
+3  A: 

You may be interested in this question (or this one), which highlights the fact that identifying valid email addresses via regexps is a very hard problem to solve (if at all solvable)

Brian Agnew
A: 

A little Google search gave me this : http://www.regular-expressions.info/email.html

Fabien Ménager
A: 

You may be interested in having a look at this page it list regular expressions for validating email address that cover more general cases.

Nadia Alramli
A: 

It would be best to use:

var pattern = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,4}$/;

This allows domains such as: whatever.info (4 letters at the end)

Also to test, use

pattern.test("[email protected]")

returns true if it works

http://www.w3schools.com/js/js_obj_regexp.asp

Alex V
+1  A: 

I've been using this function for a while. it returns a boolean value.

// Validates email address of course.
function validEmail(e) {
    var filter = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
    return String(e).search (filter) != -1;
}
rcastera