0

With this RegExp I can easily check if an email is valid or not:

RegExp(/^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/);

However, this just return true for such addresses:

[email protected]

I also want to accept:

*@example.com

What changes I need to apply on my RegExp?

Thanks in advance

1

3 Answers 3

3

To answer your question literally, you can "augment" your regex:

RegExp(/^([\w.*-]+@([\w-]+\.)+[\w-]{2,4})?$/);

But this is a terrible regex for e-mail validation. Regex is the wrong tool for this. Why do you insist on doing it this way?

5
  • I'm gonan use Regex for client side email validation(JS), on server side I'm using FILTER_VAR with PHP, what's the next way for the email validation using Javascript? and why it's terrible? could this not accept some valid email addresses?
    – behz4d
    Commented Sep 24, 2012 at 12:06
  • This accepts [email protected], I guess the /^[\w-\.\d*]+@[\w\d]+(\.\w{2,4})$/ is better since it doesn't accept [email protected]
    – behz4d
    Commented Sep 24, 2012 at 12:11
  • @behz4d: Your regex only rejects that address because it (the regex) contains a syntax error. The dash in your character class before the @ is in the wrong position and is therefore ignored. Therefore, it doesn't accept any dash before the @. Commented Sep 24, 2012 at 12:49
  • I just checked, it allows dashes before @
    – behz4d
    Commented Sep 26, 2012 at 6:25
  • If it does, then it allows the same matches as my regex (besides the *, of course). Commented Sep 26, 2012 at 6:30
1

A couple of things: to accept *@foo.bar:

var expression = /^([\w-\.*]+@([\w-]+\.)+[\w-]{2,4})?$/;//no need to pass it to the RegExp constructor

But this expression does accept [email protected], but then again, regex and email aren't all too good a friends. But based on your expression, here's a slightly less unreliable version:

var expression = /^[\w-\.\d*]+@[\w\d]+(\.\w{2,4})$/;

There is an expression that validates all valid types of email addresses, somewhere on the net, though. Look into that, to see why regex validating is almost always going to either exclude valid input or be too forgiving

1

Checking email addresses is not that straightforward, cf. RFC 822, sec 6.1.

A good list of regexes can be found at http://www.regular-expressions.info/email.html, describing tradeoffs between RFC conformance and practicality.

Not the answer you're looking for? Browse other questions tagged or ask your own question.