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?

Sign up to request clarification or add additional context in comments.

5 Comments

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?
This accepts [email protected], I guess the /^[\w-\.\d*]+@[\w\d]+(\.\w{2,4})$/ is better since it doesn't accept [email protected]
@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 @.
I just checked, it allows dashes before @
If it does, then it allows the same matches as my regex (besides the *, of course).
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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.