How to Validate an Email Address in JavaScript

How can I validate an email address in JavaScript?

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

const validateEmail = (email) => {
return String(email)
.toLowerCase()
.match(
/^(([^<>()[\]\\.,;:\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,}))$/
);
};

Here's the example of a regular expression that accepts unicode:

const re =
/^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{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:

const validateEmail = (email) => {
return email.match(
/^(([^<>()[\]\\.,;:\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,}))$/
);
};

const 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;
}

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

<label for="email">Enter an email address: </label>
<input id="email" />
<h2 id="result"></h2>

JavaScript Regular Expression Email Validation

If you define your regular expression as a string then all backslashes need to be escaped, so instead of '\w' you should have '\\w'.

Alternatively, define it as a regular expression:

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

BTW, please don't validate email addresses on the client-side. Your regular expression is way too simple to pass for a solid implementation anyway.

See the real thing here: http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html

Validate email address textbox using JavaScript

Assuming your regular expression is correct:

inside your script tags

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

if (reg.test(emailField.value) == false)
{
alert('Invalid Email Address');
return false;
}

return true;

}

in your textfield:

<input type="text" onblur="validateEmail(this);" />

how can i validate a gmail or yahoo email Address using java script and html

The logic of your if is incorrect. You're using || which means OR while you should be using && which means AND.

This is because what you want to do, translated in english is:
If the email doesn't contain @gmail AND the email doesn't contain @yahoo , then give error.

So change your code to

if(email.indexOf(gmail) == -1 && email.indexOf(yahoo) == -1 ){

Furthermore, how you search for @gmail. is not a good method, as you might encounter fake domains like @gmail.myfakedomain.com and you're not considering .ymail.com You could probably be more precise by using a full list of valid domains, e.g. from here and then match the domain exactly instead of doing a string search with indexOf.

e.g.

const singupVlidation = ()=>{
// Define list of valid domains as an array
let domain_list = ['gmail.com', 'googlemail.co.uk', 'ymail.com', 'yahoo.com', 'yahoo.it', '......etc'];
let email = document.forms['customerinfo']['email'].value;
// Extract full domain from the email address
let domain = email.substring(email.lastIndexOf("@") +1);
// Check if the domain is present in the array of valid domains
if (domain_list.includes(domain)) {
window.location.href="singin.html";
return true;
} else {
alert('invalid Email address, please correct')
return false;
}
}

How to validate email address match with website domain?

You can use URL regex by Crockford

Getting only last two parts of domain name is optional, you can use it if you want to convert ww2.mobile.gmail.com into gmail.com. This logic will affect domain names like .co.in as @samanime points out

var parse_url = /^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/;var url = 'www.mobile.ora.co.in:80/goodparts?q#fragment';
var result = parse_url.exec(url);
var hostName = result[3];
console.log("host name: ", hostName);
lastTwo = hostName.split('.');lastTwo = lastTwo.length>2?lastTwo.slice(Math.max(lastTwo.length - 2, 1)) : lastTwo;onlyMainDomain = lastTwo.join('.');
console.log('only main domain:', onlyMainDomain);
var email = "someone@ora.co.in";
var emailDomain = email.split('@')[1];
console.log('email domain:', emailDomain);
console.log("valid?" , emailDomain === onlyMainDomain);
//check if email domain is a child of hostName
emailDomainRev = emailDomain.split('.').reverse();hostNameRev = hostName.split('.').reverse();var emailDomainIsChildOfHostName = true;
if(emailDomainRev.length > hostNameRev.length){ emailDomainIsChildOfHostName = false; }else{ emailDomainIsChildOfHostName = emailDomainRev.reduce(function(acc, item, index){ return acc && (item === hostNameRev[index]); },true); }console.log("email domain is a child of host name:", emailDomainIsChildOfHostName);

Email Validation: JavaScript

First, there is an error inside the validEmail function. Try this instead :