By pix0r


2008-09-05 16:10:11 8 Comments

Is there a regular expression to validate an email address in JavaScript?

30 comments

@Colonel Panic 2013-07-14 18:15:44

All email addresses contain an 'at' (i.e. @) symbol. Test that necessary condition:

email.indexOf("@") > 0

Don't bother with anything more complicated. Even if you could perfectly determine whether an email is RFC-syntactically valid, that wouldn't tell you whether it belongs to the person who supplied it. That's what really matters.

To test that, send a validation message.

@iwazovsky 2015-04-26 10:14:10

what if there will be more than one '@' symbol? other restricted symbols? This validation cannot be trusted...

@Ebrahim 2020-07-07 14:55:36

Most of the answers here are not linter friendly, it's a mess! Some of them are also out-dated! After a lot of time spending, I decided to use an external library named email-validator, install it easily by npm for example and import/require it in your own project:

https://www.npmjs.com/package/email-validator

//NodeJs
const validator = require("email-validator");
validator.validate("[email protected]"); // true

//TypeScript/JavaScript
import * as EmailValidator from 'email-validator';
EmailValidator.validate("[email protected]"); // true

@Stefan 2020-10-20 15:02:32

It's not the answer to the question, but it helped me and saved my time. This email-validator package seem to help round about half a million other (downloads) per week. So worth to mention and deserves some upvotes.

@Rohan Devaki 2020-06-28 06:43:32

if (rules.isEmail) {
            const pattern = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
            isValid = pattern.test(value) && isValid
        }

You can use this for Email validaiton .

@Toto 2020-06-28 08:59:48

I don't see unicode in your answer. Also, have a look at these sites: TLD list; valid/invalid addresses; regex for RFC822 email address

@Rohan Devaki 2020-06-29 12:40:00

But this is the thing I used in my react and redux app for email validation it works for me ,and this is said by my instructor also, did you try implementing it?

@Toto 2020-06-29 12:46:47

Have you looked at the links I've provided? Your regex doesn't match .СРБ TLD, for example. It doesn't match [email protected] that is perfectly valid but it match '@a.a that is not valid. regex101.com/r/Kvotoc/1

@sectrean 2008-09-05 16:15:34

Using regular expressions is probably the best way. You can see a bunch of tests here (taken from chromium)

function validateEmail(email) {
    const re = /^(([^<>()\[\]\\.,;:\[email protected]"]+(\.[^<>()\[\]\\.,;:\[email protected]"]+)*)|(".+"))@((\[[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,}))$/;
    return re.test(String(email).toLowerCase());
}

Here's the example of regular expresion that accepts unicode:

const re = /^(([^<>()\[\]\.,;:\[email protected]\"]+(\.[^<>()\[\]\.,;:\[email protected]\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\[email protected]\"]+\.)+[^<>()[\]\.,;:\[email protected]\"]{2,})$/i;

But keep in mind that one should not rely only upon JavaScript validation. JavaScript can easily be disabled. This should be validated on the server side as well.

Here's an example of the above in action:

function validateEmail(email) {
  const re = /^(([^<>()[\]\\.,;:\[email protected]\"]+(\.[^<>()[\]\\.,;:\[email protected]\"]+)*)|(\".+\"))@((\[[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,}))$/;
  return re.test(email);
}

function validate() {
  const $result = $("#result");
  const email = $("#email").val();
  $result.text("");

  if (validateEmail(email)) {
    $result.text(email + " is valid :)");
    $result.css("color", "green");
  } else {
    $result.text(email + " is not valid :(");
    $result.css("color", "red");
  }
  return false;
}

$("#validate").on("click", validate);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form>
  <p>Enter an email address:</p>
  <input id='email'>
  <button type='submit' id='validate'>Validate!</button>
</form>

<h2 id='result'></h2>

@Randal Schwartz 2010-09-08 02:34:23

This regex eliminates valid, in-use emails. Do not use. Google for "RFC822" or "RFC2822" to get a proper regex.

@Vroo 2012-10-26 06:32:11

This doesn't even accept the examples in RFC 822. Some simple cases it doesn't match a\@[email protected], a(b)@c.com. See the RFC for more. Here's a regex that won't reject any valid addresses [^@][email protected][^@]+\.[^@]+ and protects against common errors.

@Kevin Fegan 2014-02-01 08:49:15

You cannot validate email addresses, period. The only one who can validate an email address is the provider of the email address. For example, this answer says these email addresses: %[email protected], "%2"@gmail.com, "a..b"@gmail.com, "a_b"@gmail.com, [email protected], [email protected] , [email protected] are all valid, but Gmail will never allow any of these email addresses. You should do this by accepting the email address and sending an email message to that email address, with a code/link the user must visit to confirm validity.

@Cleanshooter 2015-04-08 15:02:14

These days Javascript can be run on a server so for those thinking this is only relevant for client side validation you are wrong. And to those who say its not possible to validate an email I believe your missing the point of validation in general. YOU WILL NEVER write validation for a form to ensure that everything is 100% perfect for two main reasons: 1. It would take more time than it would be worth to write the logic and 2. There will always be an edge case where bad data could get submitted. The reason we validate is to encourage proper data submission and prevent mistakes.

@adriaan 2015-05-18 13:47:42

Watch out, this is invalid: re.test("[email protected]")

@Felipe Skinner 2015-11-06 15:24:37

That answer does not accept a gmail valid email like "[email protected]"

@fromthehills 2020-08-30 21:51:42

Perhaps it should be.phrased "... validate email format .." per Kevin's comment. Also now with HTML5 there is.the type="email".

@Mar 2020-09-28 07:54:57

This regex is not secure and potential for ReDoS. check: stackblitz.com/edit/js-nllx8y

@Ryan Holton 2020-10-07 15:49:21

How can I put this as a pattern on my input instead?

@AmigoJack 2020-10-15 22:38:26

All this JS and RegEx without even checking for valid lengths (64 octets max + @ + 255 octets max) as per RFC 3696 §3.

@Jaskaran Singh 2020-04-13 00:46:58

If you get this error: Using regular expressions is security-sensitive.

Then here is what you are looking for.This solution is free from " Regular expression Denial of Service (ReDoS) "

Regex to validate emails without (ReDoS):

/^[a-z0-9](?!.*?[^\na-z0-9]{2})[^\[email protected]][email protected][^\[email protected]]+\.[^\[email protected]]+[a-z0-9]$/

Please let me know if this solutions works for you. Thanks.

@C. Lee 2012-02-09 02:22:32

I've slightly modified Jaymon's answer for people who want really simple validation in the form of:

[email protected]

The regular expression:

/\[email protected]\S+\.\S+/

Example JavaScript function:

function validateEmail(email) 
    {
        var re = /\[email protected]\S+\.\S+/;
        return re.test(email);
    }
    
console.log(validateEmail('[email protected]'));

@user83358 2012-07-30 18:20:04

You can implement something 20x as long that might cause problems for a few users and might not be valid in the future, or you can grab ImmortalFirefly's version to make sure they at least put in the effort to make it look real. Depending on your application it may be more likely to come across someone will get mad because you don't accept their unconventional email, rather than someone who causes problems by entering email addresses that don't really exist (which they can do anyways by entering a 100% valid RFC2822 email address but using an unregistered username or domain). Upvoted!

@OregonTrail 2012-08-09 14:58:13

@ImmortalFirefly, the regex you provided will actually match [email protected]@example.com. Try pasting your line into a JavaScript console. I believe your intention was to match only the entire text, which would require the beginning of text '^' and end of text '$' operators. The one I'm using is /^[^\[email protected]][email protected][^\[email protected]]+\.[^\[email protected]]+$/.test('[email protected]@example.com')

@user1843640 2020-02-03 15:38:01

I prefer to keep it simple and keep my users happy. I also prefer code which is easy to understand. RegEx is not.

function isValidEmail(value) {
    const atLocation = value.lastIndexOf("@");
    const dotLocation = value.lastIndexOf("."); 
    return (
        atLocation > 0 &&
        dotLocation > atLocation + 1 &&
        dotLocation < value.length - 1
    );
};
  • Get the location of the last "@" and the last "."
  • Make sure the "@" is not the first char (there is something before it)
  • Make sure the "." is after the "@" and that there is at least one char between them
  • Make sure there is at least a single char after the "."

Will this allow invalid email addresses to pass? Sure, but I don't think you need much more for a good user experience that allows you to enable/disable a button, display an error message, etc. You only know for sure that an email address is valid when you attempt to send an email to that address.

@endyourif 2020-01-26 19:36:41

Wow there are a lot of answers that contain slightly different regular expressions. I've tried some many that I've got different results and a variety of different issues with all of them.

For UI validation, I'm good with the most basic check of looking for an @ sign. It's important to note, that I always do server-side validation with a standard "validate email" that contains a unique link for the user to confirm their email address.

if (email.indexOf('@') > 0)

I have purposely chosen 0 even with zero-based as it also ensures there is a single character before the @.

@Mattia Rasulo 2020-01-24 17:32:27

Use W3C especially created regular expression.

Reference with full explanation of the RegEx:

https://www.w3resource.com/javascript/form/email-validation.php

/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(emailValue)

If you use Node you can use this in the back-end as well as the front-end.

I don't know other back-end languages so I cannot evaluate for other use cases.

@Xizam 2020-03-24 11:15:49

This regex fails on '[email protected]' and on '[email protected]'. Do not use.

@Eboubaker 2019-11-17 22:22:24

These will work with the top used emails(they match exactly the rules of each one).

Gmail
/^[a-z]((?!\.\.)([a-z\.])){4,28}[a-z0-9]@gmail.com$/i

Yahoo
/^[a-z]((?!\.\.)([\w\.])){3,30}[\w]@yahoo.com$/i

Outlook/Hotmail
/[a-z]((?!\.\.)([\w\.])){0,62}[\w]@(outlook.com|hotmail.com)$/i

@Toto 2019-11-18 12:50:48

Do you know that \w already includes \d and _? Please, have a look at these sites: TLD list; valid/invalid addresses; regex for RFC822 email address

@Eboubaker 2019-11-21 16:30:49

@Toto that's right, i don't know how i lost it there, i actually used this regex in my database handaling :\, thanks again.

@David Wheatley 2020-01-21 17:36:49

Gmail's domain is not @google.com, it's @gmail.com or (for very old accounts) @googlemail.com

@Renish Gotecha 2019-12-27 08:52:53

In my case i want to avoid ~ and # that's why i have use another solution Click Here For more information

function validEmail(email){
  const regex = /^((?!\.)[\w-_.]*[^.])(@\w+)(\.\w+(\.\w+)?[^.\W])$/;
  return regex.test(email);
}

function validEmail(email){
  const regex = /^((?!\.)[\w-_.]*[^.])(@\w+)(\.\w+(\.\w+)?[^.\W])$/;
  return regex.test(email);
}

const emails = [
'[email protected]',
'[email protected]',
'[email protected]',
'pio_#[email protected]',
'[email protected]#factory.com',
'[email protected]#om',
'[email protected]*om',
'pio^[email protected]'
]

for(const email of emails){
  document.write(email+' : '+validEmail(email)+'</br>');
}

@tecnocrata 2018-12-12 18:05:03

You could also use the New Regex class and make this way:

function validateEmail( str ) { return new RegExp( /([\w\.\-_]+)?\[email protected][\w-_]+(\.\w+){1,}/, 'igm' ).test( str ); }

reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

@rktuxyn 2019-11-26 10:09:08

You may try RegExp

function isValidEmail( value ) {
	return /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,5}$/.test( value );
}

console.log( isValidEmail("[email protected]") )

@Toto 2019-11-26 13:50:55

Please, have a look at these sites: TLD list; valid/invalid addresses; regex for RFC822 email address

@Purvi Barot 2019-11-04 04:41:12

for email validation you can create your custom function and use regex syntax for validate email:

function validateEmail(email){
        var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

       //your custom code here to check your email address 

}

@Toto 2019-11-18 12:51:00

Please, have a look at these sites: TLD list; valid/invalid addresses; regex for RFC822 email address

@jimmont 2019-09-17 03:00:32

Use the browser/runtime to handle parsing the input by prepending a protocol and pass it to the URL API, trapping any errors and check the resulting username and hostname properties of the result. It will handle basically all transformations and possibilities (punycode of character sets, etc). This only establishes that the input is parsable, not that is valid--that is only possible through checking if the destination machine receives messages for that alias. This provides a close (imo reasonable) guess though, and can be expanded to be more specific and realistic if you're comfortable both maintaining it and also risking invalid rejections. (Note it doesn't attempt to address IPv4 or IPv6 addresses, simply the broad range of customer-facing scenarios using a domain.)

function validEmail(email=''){
    var $0, url, isValid = false, emailPatternInput = /^[^@]{1,64}@[^@]{4,253}$/, emailPatternUrl = /^[^@]{1,64}@[a-z][a-z0-9\.-]{3,252}$/i;
    email = email.trim();
    try{
        url = new URL('http://'+email);
        $0 = `${url.username}@${url.hostname}`;
        isValid = emailPatternInput.test( email );
        if(!isValid) throw 'invalid email pattern on input:' + email;
        isValid = emailPatternUrl.test( $0 );
        if(!isValid) throw 'invalid email pattern on url:' + $0;
        console.log(`email looks legit "${email}" checking url-parts: "${$0 === email ? '-SAME-':$0}"`);
    }catch(err){
        console.error(`probably not an email address: "${email}"`, err);
    };
    return isValid;
}

['[email protected]はじめよう.みんな', '[email protected]', '[email protected]', 'Jean+Franç[email protected]','هيا@יאללה', '试@例子.测试.مثال.آزمایشی', '[email protected]@really', 'no'].forEach(email=>console.log(validEmail(email), email));

This is the both the simplest and most generally permissive example I can come up with. Please edit it in cases where it can be made to be more accurate while maintain its simplicity and reasonable generally permissive validity.

Also see MDN URL docs URL, window.URL and Nodejs for URL APIs.

@Idan 2019-08-05 16:23:31

I add my Regex - i solved for me more little issues like characters from other languages or capital letters

^[a-zA-Z0-9][a-zA-Z0-9-_\.][email protected]([a-zA-Z]|[a-zA-Z0-9]?[a-zA-Z0-9-]+[a-zA-Z0-9])\.[a-zA-Z0-9]{2,10}(?:\.[a-zA-Z]{2,10})?$

@B. Bohdan 2019-03-01 16:27:40

There is my version of an email validator. This code is done with object-oriented programming and realized as a class with static methods. You will find two versions of the validators: strict(EmailValidator.validate) and kind(EmailValidator.validateKind).

The first throws an error if an email is invalid and returns email otherwise. The second returns Boolean value that says if an email is valid. I prefer the strict version in most of the cases.

export class EmailValidator {
    /**
     * @param {string} email
     * @return {string}
     * @throws {Error}
     */
    static validate(email) {
        email = this.prepareEmail(email);

        const isValid = this.validateKind(email);

        if (isValid)
            return email;

        throw new Error(`Got invalid email: ${email}.`);
    }

    /**
     * @param {string} email
     * @return {boolean}
     */
    static validateKind(email) {
        email = this.prepareEmail(email);

        const regex = this.getRegex();

        return regex.test(email);
    }

    /**
     * @return {RegExp}
     * @private
     */
    static getRegex() {
        return /^(([^<>()\[\]\\.,;:\[email protected]"]+(\.[^<>()\[\]\\.,;:\[email protected]"]+)*)|(".+"))@((\[[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,}))$/;
    }

    /**
     * @param {string} email
     * @return {string}
     * @private
     */
    static prepareEmail(email) {
        return String(email).toLowerCase();
    }
}

To validate an email you can follow these ways:

// First way.

try {
    EmailValidator.validate('[email protected]');
} catch (e) {
    console.error(e.message);
}
// Second way.

const email = '[email protected]';
const isValid = EmailValidator.validateKind(email);

if (isValid)
    console.log(`Email is valid: ${email}.`);
else
    console.log(`Email is invalid: ${email}.`);

@Antonio 2019-04-25 14:46:18

General email regex (RFC 5322 Official Standard): https://emailregex.com/

JavaScript:

/^(([^<>()\[\]\\.,;:\[email protected]"]+(\.[^<>()\[\]\\.,;:\[email protected]"]+)*)|(".+"))@((\[[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,}))$/

@Nicolas Zozol 2019-06-05 10:14:43

If you want something a human can read and maintain, I would recommend Masala Parser (I'm one of the creators of it).

import {C,Streams} from '@masala/parser'

const illegalCharset = ' @\u00A0\n\t';
const extendedIllegalCharset = illegalCharset + '.';


// Assume '[email protected]'
export function simpleEmail() {

    return C.charNotIn(illegalCharset).rep() // 'nicolas'
        .then(C.char('@'))
        .then(subDns())  //'internal.masala.co.'
        .then(C.charNotIn(extendedIllegalCharset).rep()) //'uk'
        .eos(); // Must be end of the char stream
}

// [email protected] => extract 'internal.masala.co.'
function  subDns() {
    return C.charNotIn(extendedIllegalCharset).rep().then(C.char('.')).rep()
}

function validateEmail(email:string) {
    console.log(email + ': ' + (simpleEmail().parse(Streams.ofString(email)).isAccepted()));
}


validateEmail('[email protected]'); // True
validateEmail('[email protected]'); // False, trailing "."

If you want to accept the ultimate ugly email version, you can add in quotes in the first part:


function inQuote() {
    return C.char('"')
        .then(C.notChar('"').rep())
        .then(C.char('"'))
}

function allEmail() {

    return inQuote().or(C.charNotIn(illegalCharset))
        .rep() // repeat (inQuote or anyCharacter)
        .then(C.char('@'))
        .then(subDns())
        .then(C.charNotIn(extendedIllegalCharset).rep())
        .eos() // Must be end of the character stream
        // Create a structure
        .map(function (characters) { return ({ email: characters.join('') }); });
}

'"nicolas""love-quotes"@masala.co.uk' is officially valid, but should it be in your system?

At least with Masala, you give yourself a chance to understand it. And so for the next year, colleague.

@Prabhat Kasera 2016-12-22 07:44:49

Regex for validating email address

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

@Anoop 2011-10-17 08:23:34

HTML5 itself has email validation. If your browser supports HTML5 then you can use the following code.

<form><input type="email" placeholder="[email protected]" required>
    <input type="submit">
</form>

jsFiddle link

From the HTML5 spec:

A valid e-mail address is a string that matches the email production of the following ABNF, the character set for which is Unicode.

email   = 1*( atext / "." ) "@" label *( "." label )
label   = let-dig [ [ ldh-str ] let-dig ]  ; limited to a length of 63 characters by RFC 1034 section 3.5
atext   = < as defined in RFC 5322 section 3.2.3 >
let-dig = < as defined in RFC 1034 section 3.5 >
ldh-str = < as defined in RFC 1034 section 3.5 >

This requirement is a willful violation of RFC 5322, which defines a syntax for e-mail addresses that is simultaneously too strict (before the "@" character), too vague (after the "@" character), and too lax (allowing comments, whitespace characters, and quoted strings in manners unfamiliar to most users) to be of practical use here.

The following JavaScript- and Perl-compatible regular expression is an implementation of the above definition.

/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-][email protected][a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/

@Jason 2011-11-12 00:08:32

this is good, but the problem with this is that it must be inside a form tag and submitted by a submit input, which not everyone has the luxury of doing. Also, you can't really style the error message.

@Pax 2019-05-27 09:54:58

Search for the @ sign in the input field.

@oligofren 2019-09-24 09:35:16

This! This is the only valid check you can really do that doesn't complicate things needlessly. If you really want to know if the email is valid, send the user an email.

@Raheel 2019-04-23 08:43:49

I am using this function

/**
 * @param {*} email
 */
export const validateEmail = email => {
    return new RegExp(/[\w-][email protected]([\w-]+\.)+[\w-]+/gm).test(email);
};

@oligofren 2019-09-24 09:36:58

Doesn't work for Unicode. validateEmail('køkø@gmail.com') === false. Forget validation using checks like this. Test for @ and just send the user an email.

@Ryan Taylor 2012-11-01 14:06:27

Do this:

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

Why? It's based on RFC 2822, which is a standard ALL email addresses MUST adhere to. And I'm not sure why you'd bother with something "simpler"... you're gonna copy and paste it anyway ;)

Often when storing email addresses in the database I make them lowercase and, in practice, regexs can usually be marked case insensitive. In those cases this is slightly shorter:

[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 an example of it being used in JavaScript (with the case insensitive flag i at the end).

var emailCheck=/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i;
console.log( emailCheck.test('[email protected]') );

Note:
Technically some emails can include quotes in the section before the @ symbol with escape characters inside the quotes (so your email user can be obnoxious and contain stuff like @ and "..." as long as it's written in quotes). NOBODY DOES THIS EVER! It's obsolete. But, it IS included in the true RFC 2822 standard, and omitted here.

More info: http://www.regular-expressions.info/email.html

@karlgzafiris 2019-02-23 20:19:12

Here's how I do it. I'm using match() to check for the standard email pattern and I'm adding a class to the input text to notify the user accordingly. Hope that helps!

$(document).ready(function(){
  $('#submit').on('click', function(){
      var email = $('#email').val();
      var pat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
      if (email.match(pat)){
        $('#email')
          .addClass('input-valid');
        return false;
      } else {
        $('#email')
        	.addClass('input-error')
          .val('');
        return false;
      }
  });
});
.input-error {
  border: 1px solid red;
  color: red;
}

.input-valid {
  border: 1px solid green;
  color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
    <input type="text" id="email" placeholder="[email protected]" class="">
    <input type="submit" id="submit" value="Send"/>
</form>

@Iman Hejazi 2019-03-04 16:48:07

Have you ever tried DeBounce Email Validation? I suggest taking a look at this.

@ranieribt 2019-01-28 20:49:22

You cold use https://github.com/chriso/validator.js and simply do:

var validator = require('validator');

validator.isEmail('[email protected]'); //=> true

Note that this can work on the client.

@isapir 2019-01-11 20:04:26

Here is the recommended Regex pattern for HTML5 on MDN:

Browsers that support the email input type automatically provide validation to ensure that only text that matches the standard format for Internet e-mail addresses is entered into the input box. Browsers that implement the specification should be using an algorithm equivalent to the following regular expression:

/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-][email protected][a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}
[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email#Validation

@Iman Hejazi 2019-03-09 12:44:16

Good. Have you ever tried other validation methods like PHP or API services? Like DeBounce Email Validation Tool.

@Jaymon 2008-09-07 21:21:46

Wow, there are lots of complexity here. If all you want to do is just catch the most obvious syntax errors, I would do something like this:

^\[email protected]\S+$

It usually catches the most obvious errors that the user makes and assures that the form is mostly right, which is what JavaScript validation is all about.

@kommradHomer 2012-07-19 07:14:33

+1 as sending email and seeing what happens is the only real sure way to validate an email address , theres no need to do more than a simple regex match.

@Tim Franklin 2013-03-21 04:06:18

You can still keep it simple but do a little more to ensure it has a "." somewhere after the @ followed by only numbers or digits, so things like [email protected], [email protected]@, and [email protected] aren't valid... ^\[email protected]\S+[\.][0-9a-z]+$

@Sam 2013-04-10 23:51:58

I think e-mail addresses can contain spaces. It's probably better to use [email protected]+

@gtournie 2014-01-27 04:57:17

/\[email protected]\S+/.test("áéíóúý@ÁÉÍÓÚÝð") true

@meagar 2015-01-31 14:59:52

@gtournie Nobody cares. Nobody is going to enter that into an email field by accident, and that is all front-end validation is for: To prevent people from accidentally entering the wrong bit of information, such as their name, in an email field.

@Fattie 2020-10-20 15:36:06

This answer is completely correct.

@Khaliq Izrail Haxor 2018-11-19 15:33:56

The personal_info part contains the following ASCII characters.

  1. Uppercase (A-Z) and lowercase (a-z) English letters. Digits (0-9).
  2. Characters ! # $ % & ' * + - / = ? ^ _ ` { | } ~
  3. Character . ( period, dot or fullstop) provided that it is not the first or last character and it will not come one after the other.

The domain name [for example com, org, net, in, us, info] part contains letters, digits, hyphens, and dots.

 function ValidateEmail(mail) 
{
 if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(myForm.emailAddr.value))
  {
    return (true)
  }
    alert("You have entered an invalid email address!")
    return (false)
}

@Miloš Rašić 2011-03-02 11:26:02

Correct validation of email address in compliance with the RFCs is not something that can be achieved with a one-liner regular expression. An article with the best solution I've found in PHP is What is a valid email address?. Obviously, it has been ported to Java. I think the function is too complex to be ported and used in JavaScript. JavaScript/node.js port: https://www.npmjs.com/package/email-addresses.

A good practice is to validate your data on the client, but double-check the validation on the server. With this in mind, you can simply check whether a string looks like a valid email address on the client and perform the strict check on the server.

Here's the JavaScript function I use to check if a string looks like a valid mail address:

function looksLikeMail(str) {
    var lastAtPos = str.lastIndexOf('@');
    var lastDotPos = str.lastIndexOf('.');
    return (lastAtPos < lastDotPos && lastAtPos > 0 && str.indexOf('@@') == -1 && lastDotPos > 2 && (str.length - lastDotPos) > 2);
}

Explanation:

  • lastAtPos < lastDotPos: Last @ should be before last . since @ cannot be part of server name (as far as I know).

  • lastAtPos > 0: There should be something (the email username) before the last @.

  • str.indexOf('@@') == -1: There should be no @@ in the address. Even if @ appears as the last character in email username, it has to be quoted so " would be between that @ and the last @ in the address.

  • lastDotPos > 2: There should be at least three characters before the last dot, for example [email protected].

  • (str.length - lastDotPos) > 2: There should be enough characters after the last dot to form a two-character domain. I'm not sure if the brackets are necessary.

Related Questions

Sponsored Content

28 Answered Questions

[SOLVED] What does "use strict" do in JavaScript, and what is the reasoning behind it?

54 Answered Questions

62 Answered Questions

[SOLVED] How do I include a JavaScript file in another JavaScript file?

76 Answered Questions

31 Answered Questions

[SOLVED] Regular expression to match a line that doesn't contain a word

98 Answered Questions

[SOLVED] How can I remove a specific item from an array?

  • 2011-04-23 22:17:18
  • Walker
  • 7233968 View
  • 8733 Score
  • 98 Answer
  • Tags:   javascript arrays

58 Answered Questions

[SOLVED] How do I redirect to another webpage?

86 Answered Questions

[SOLVED] How do JavaScript closures work?

49 Answered Questions

[SOLVED] Validate decimal numbers in JavaScript - IsNumeric()

54 Answered Questions

Sponsored Content