0
//if HTML5 input email input is not supported
if(type == 'email'){    
    if(!Modernizr.inputtypes.email){ 
         var emailRegEx = /^([a-zA-Z0-9_\.\-])+\@([a-zA-Z0-9\-])+\.+([a-zA-Z0-9]{2,4})+$/;              
         if( !emailRegEx.test(value) ){ 
            this.focus();
            formok = false;
            errors.push(errorMessages.email + nameUC);
            return false;
        }
    }
}

This is my javascript regex for checking if e-mail format is correct. But When I try it myself it shows no error for any ..@.. It does not check .com or whatever in the end. What am I doing wrong?

1
  • 5
    I smell too much uppercase in your question title. And this regex is horrible. There are TLDs which are longer than 4 characters and + would be perfectly valid in the local part of the email address. It also fails on IDNs. Commented Apr 29, 2012 at 10:51

1 Answer 1

1

You need to use a regex that actually fits for an email address. Your current one is completely broken as there are tons of valid addresses it won't accept.

See http://www.regular-expressions.info/email.html for a more detailed description and arguments why a regex is not such a good idea after all.

Anyway, here's one that probably fits for your needs:

[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?

Here's what regular-expressions.info says about this regex:

We get a more practical implementation of RFC 2822 if we omit the syntax using double quotes and square brackets. It will still match 99.99% of all email addresses in actual use today.

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

1 Comment

I decided not to use regex and rely on html 5 validation for emails. It's not consistent I know and opera shows no error for . but mail doesn't come to me. But still it's usable

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.