Manish Basdeo
Manish Basdeo

Reputation: 6269

Is the following function ok to validate an email?

Just tested this function to validate an email..However,it does not validate the presence or absence of the dot in the email..Why this is happening and how can I fix this?

<script type="text/javascript">
  function isEmail(textbox){

    var reg4 =/^(\w+)@(\w+).(\w+)$/;
    if(reg4.test(textbox.value)){

            return true;
        }

    return false;
}
</script>

Upvotes: 0

Views: 120

Answers (5)

Alnitak
Alnitak

Reputation: 339917

No, it's insufficient.

In particular, it doesn't handle all these (legal) variants:

  1. quoted user parts, e.g. "my name"@example.com

  2. Internationalised domain names (IDNs)

  3. Domains with more than two labels

  4. Domains with only one label (yes, those are legal)

  5. Hyphens in domain names

  6. user@[1.2.3.4]

Validating an e-mail address via a regexp is very hard. See section 3.4.1 of RFC 5322 for the formal syntax definition.

Upvotes: 3

Xion
Xion

Reputation: 22770

Escape the dot with backslash: \.. However, your regex would not be very good afterwards as it will not accept multiple dots in post-@ part, such as domain foo.co.uk.

All in all, I'd advise againts using regexes to validate emails as they tend to get overcomplicated ;-) Simply check for presence of @ followed by a dot, or use a similarly lenient algorithm.

Upvotes: 1

Do not use a regular expression to validate email addresses. Email addresses can include a lot of things you wouldn't imagine (like spaces), and it's more likely that the user will accidentally enter an invalid email address than an invalid one. Just check if there's an @ then send a confirmation email if you want.

From an answer to a related question:

There is no good (and realistic, see the fully RFC 822 compliant regex) regular expression for this problem. The grammar (specified in RFC 5322) is too complicated for that. Use a real parser or, better, validate by trying (to send a message).

Upvotes: 2

Digital Plane
Digital Plane

Reputation: 38264

You need to escape the dot, which normally matches any character.

var reg4 =/^(\w+)@(\w+)\.(\w+)$/;

Upvotes: 1

Fender
Fender

Reputation: 3055

the dot has a meaning in a regex

use [\.] instead of .

Upvotes: 1

Related Questions