0

Possible Duplicate:
Using a regular expression to validate an email address

I have just made a RE for email address. Its a simplest one and works well. But i want to make it more better. I mean to say that, an email address can have alphanumeric characters, underscores "_", dot "." but it cannot contain hyphen "-", semicolon ";" etc. Below is my RE that i have just made for email address.

<!DOCTYPE html>
<html>
<body>

<script>
str = "assad-ch7@Yahoo.com";

re = /[a-z0-9][@]((yahoo)|(hotmail)|(gmail))[.]((com)|(co.uk))/i; 


result = re.test(str);

document.write(result);

</script>

</body>
</html>

Furthermore, is this the right way to make an RE for an email address??

Community
  • 1
  • 1
  • You may want to add `^` and `$` to your regex ;) Also, `.` needs to be escaped if you want to match a literal dot: `co\.uk`. Further, you will want a quantifier : `[a-z0-9]+` – phant0m Dec 05 '12 at 21:32

1 Answers1

1

It's not bad if you want to limit the email addresses to those domains. There are a few fixes though

  1. Need _ and . in first character class
  2. Add + after first character class to capture all characters before @
  3. Remove @ and . from character class brackets
  4. Remove unnecessary extra parenthesis
  5. Backslash literal periods (unnecessary inside character classes)

var re = /[a-z0-9_.]+@(yahoo|hotmail|gmail)\.(com|co\.uk)/i;

Brian Cray
  • 1,277
  • 1
  • 7
  • 19