[javascript] JavaScript Regular Expression Email Validation

This code is always alerting out "null", which means that the string does not match the expression.

var pattern = "^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$"; 

function isEmailAddress(str) {

    str = "[email protected]";      

    alert(str.match(pattern)); 
    return str.match(pattern);    

}

This question is related to javascript regex

The answer is


I have been using this one....

/^[\w._-]+[+]?[\w._-]+@[\w.-]+\.[a-zA-Z]{2,6}$/

It allows that + before @ ([email protected])


Sometimes most of the registration and login page need to validate email. In this example you will learn simple email validation. First take a text input in html and a button input like this

<input type='text' id='txtEmail'/>
<input type='submit' name='submit' onclick='checkEmail();'/>

<script>
    function checkEmail() {
        var email = document.getElementById('txtEmail');
        var filter = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        if (!filter.test(email.value)) {
            alert('Please provide a valid email address');
            email.focus;
            return false;
        }
    }
</script>

you can also check using this regular expression

<input type='text' id='txtEmail'/>
<input type='submit' name='submit' onclick='checkEmail();'/>

<script>
    function checkEmail() {

        var email = document.getElementById('txtEmail');
        var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

        if (!filter.test(email.value)) {
            alert('Please provide a valid email address');
            email.focus;
            return false;
        }
    }
</script>

Check this demo output which you can check here

_x000D_
_x000D_
function checkEmail() {_x000D_
        var email = document.getElementById('txtEmail');_x000D_
        var filter = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;_x000D_
        if (!filter.test(email.value)) {_x000D_
            alert('Please provide a valid email address');_x000D_
            email.focus;_x000D_
            return false;_x000D_
        }_x000D_
    }
_x000D_
<input type='text' id='txtEmail'/>_x000D_
<input type='submit' name='submit' onclick='checkEmail();'/>
_x000D_
_x000D_
_x000D_

if email invalid then give alert message , if valid email then no alert message . for more info about regular expression

https://www.w3schools.com/jsref/jsref_obj_regexp.asp

hope it will help you


this is the one i am using on my page.

http://www.zparacha.com/validate-email-address-using-javascript-regular-expression/

/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/


Email validation is easy to get wrong. I would therefore recommend that you use Verimail.js.

Why?

  • Syntax validation (according to RFC 822).
  • IANA TLD validation
  • Spelling suggestion for the most common TLDs and email domains
  • Deny temporary email account domains such as mailinator.com
  • jQuery plugin support

Another great thing with Verimail.js is that it has spelling suggestion for the most common email domains and registered TLDs. This can lower your bounce rate drastically for users that misspell common domain names such as gmail.com, hotmail.com, aol.com, aso..

Example:

How to use it?

The easiest way is to download and include verimail.jquery.js on your page. After that, hookup Verimail by running the following function on the input-box that needs the validation:

$("input#email-address").verimail({
    messageElement: "p#status-message"
});

The message element is an optional element that displays a message such as "Invalid email.." or "Did you mean [email protected]?". If you have a form and only want to proceed if the email is verified, you can use the function getVerimailStatus as shown below:

if($("input#email-address").getVerimailStatus() < 0){
    // Invalid email
}else{
    // Valid email
}

The getVerimailStatus-function returns an integer code according to the object Comfirm.AlphaMail.Verimail.Status. As shown above, if the status is a negative integer value, then the validation should be treated as a failure. But if the value is greater or equal to 0, then the validation should be treated as a success.


Simple but powerful email validation for check email syntax :

var EmailId = document.getElementById('Email').value;
var emailfilter = /^[\w._-]+[+]?[\w._-]+@[\w.-]+\.[a-zA-Z]{2,6}$/;
if((EmailId != "") && (!(emailfilter.test(EmailId ) ) )) {
    msg+= "Enter the valid email address!<br />";
}

You may be interested in this question (or this one), which highlights the fact that identifying valid email addresses via regexps is a very hard problem to solve (if at all solvable)


I've been using this function for a while. it returns a boolean value.

// Validates email address of course.
function validEmail(e) {
    var filter = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
    return String(e).search (filter) != -1;
}

You can also try this expression, I have tested it against many email addresses.

var pattern = /^[A-Za-z0-9._%+-]+@([A-Za-z0-9-]+\.)+([A-Za-z0-9]{2,4}|museum)$/;

with more simple

Here it is :

var regexEmail = /\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
var email = document.getElementById("txtEmail");

if (regexEmail.test(email.value)) {
    alert("It's Okay")
} else {
    alert("Not Okay")

}

good luck.


function isEmailAddress(str) {
   var pattern =/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
   return pattern.test(str);  // returns a boolean 
}

You should bear in mind that a-z, A-Z, 0-9, ., _ and - are not the only valid characters in the start of an email address.

Gmail, for example, lets you put a "+" sign in the address to "fake" a different email (e.g. [email protected] will also get email sent to [email protected]).

micky.o'[email protected] would not appreciate your code stopping them entering their address ... apostrophes are perfectly valid in email addresses.

The Closure "check" of a valid email address mentioned above is, as it states itself, quite naïve:

http://code.google.com/p/closure-library/source/browse/trunk/closure/goog/format/emailaddress.js#198

I recommend being very open in your client side code, and then much more heavyweight like sending an email with a link to really check that it's "valid" (as in - syntactically valid for their provider, and also not misspelled).

Something like this:

var pattern = /[^@]+@[-a-z\.]\.[a-z\.]{2,6}/

Bearing in mind that theoretically you can have two @ signs in an email address, and I haven't even included characters beyond latin1 in the domain names!

http://www.eurid.eu/en/eu-domain-names/idns-eu

http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx


var emailRegex = /^[A-Z0-9_'%=+!`#~$*?^{}&|-]+([\.][A-Z0-9_'%=+!`#~$*?^{}&|-]+)*@[A-Z0-9-]+(\.[A-Z0-9-]+)+$/i;
if(emailRegex.test('yoursamplemail'))
alert('valid');
else
alert('invalid');

You may be interested in having a look at this page it list regular expressions for validating email address that cover more general cases.


Little late to the party, but here goes nothing...

function isEmailValid(emailAdress) {
    var EMAIL_REGEXP = new RegExp('^[a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,15})$', 'i');
    return EMAIL_REGEXP.test(emailAdress)
}

http://jsfiddle.net/yrshaikh/xvd6H/


It would be best to use:

var pattern = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,20}$/;

This allows domains such as: whatever.info (4 letters at the end)

Also to test, using

pattern.test("[email protected]")

returns true if it works

http://www.w3schools.com/js/js_obj_regexp.asp


You can add a function to String Object

//Add this wherever you like in your javascript code
String.prototype.isEmail = function() {
    return !!this.match(/^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/);
}

var user_email = "[email protected]";

if(user_email.isEmail()) {
    //Email is valid !
} else {
    //Email is invalid !
}