Reputation: 31290
I'd like to check if the user input is an email address in JavaScript, before sending it to a server or attempting to send an email to it, to prevent the most basic mistyping. How could I achieve this?
Upvotes: 5470
Views: 4862235
Reputation: 2543
Use the URL
interface in JavaScript to parse the address in the minimum practical expected format user@host
then check that it looks reasonable. Note that this handles punycode, internationalization, as shown in the test samples below, and can optionally make MX record lookups related to that address before sending something by email (like a token) as a final validation step that the address exists. This approach doesn't make any attempt at solving for related RFC's and works in modern browsers, Deno and Cloudflare workers.
https://developer.mozilla.org/docs/Web/API/URL
an example with simple tests:
async function validEmail(address, checkDomain=false){
const emailPattern = /^[^@]{1,64}@[a-z0-9][a-z0-9\.-]{3,252}$/i;
let email, valid = false, error, same = false, domain;
try{
// URL handles punycode, etc using browser implementation
const url = new URL(`http://${ address }`);
const { username, hostname } = url;
email = `${username}@${hostname}`;
same = address === email;
valid = emailPattern.test( email );
if(!valid) throw new Error(`invalid email ${ email }`);
if(checkDomain){
// function hasMX(dns){ return dns?.[0]?.exchange ? true: false; }
// domain = await Deno.resolveDns(hostname, 'MX').then(hasMX).catch(hasMX);
function hasMX(dns){ return dns?.Answer?.[0]?.data ? true: false; }
domain = await fetch(`https://cloudflare-dns.com/dns-query?name=${ hostname }&type=MX`, {headers:{Accept: "application/dns-json"}}).then(res=>res.json()).then(hasMX).catch(hasMX);
}
}catch(fail){
error = fail;
};
return {email, same, valid, error, domain};
}
[
'user+this@はじめよう.みんな'
, '[email protected]'
, 'stuff@things'
, '[email protected]'
, 'Jean+Franç[email protected]','هيا@יאללה'
, '试@例子.测试.مثال.آزمایشی'
, 'not@@really'
, 'no'
].forEach(async address=>{
let result = await validEmail(address);
console.log(result, address);
});
[
'[email protected]'
, '[email protected]'
].forEach(async address=>{
let result = await validEmail(address, true);
console.log(result, address);
});
Upvotes: 3
Reputation: 10702
Using regular expressions is probably the best way of validating an email address in JavaScript. View a bunch of tests on JSFiddle 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,}))$/
);
};
The following is an example of a regular expression that accepts unicode.
const re =
/^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;
Keep in mind that one should not rely on JavaScript validation alone, as JavaScript can be easily disabled by the client. Furthermore, it is important to validate on the server side.
The following snippet of code is an example of JavaScript validating an email address on the client side.
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 invalid.');
$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 email address</label>
<input id="email" type="email">
<p id="result"></p>
Upvotes: 6643
Reputation: 783
The answer to this question (if you stood back and really thought about it) is that you can't really prevent a user from mistyping their e-mail. Everybody is providing answers that match all the possible letters but nobody has really taken into account the full myriad of characters that can be used.
I refer you to this post and the answer explaining the amount of characters that can be accepted:- Remove invalid characters from e-mail
You can't predict if the letters are the exact way the user intended them to be - which is the most common mistake.. missing a letter out or typing the wrong letter.
Ultimately, no matter what you do in Javascript you will always need your backend script to check if the e-mail was sent successfully too and it will probably have a validation process in place too.
So if you wanted to ensure it was some sort of e-mail address and not their username you only really need to check if there's an @ symbol in there and at least 1 dot and leave all the rest to your backend code.
I have provided a very basic function that demonstrates a delayed check for real-time input and an instant check. Javascript is acting as a first checkpoint to validate the basics to save posting invalid content and annoying the user.
It will always assume the bigger check is at the backend though.
// Very simple, non-library dependent client-side e-mail validator
var emailv = {
// Timeout handler for checkDelay()
to: null,
// The core function that takes a string and validates it
check : function(em){
// Check 1 - The split ensures there's only one @
var c1 = em.split('@').length == 2;
// Check 2 - Must be at least 1 dot too
var c2 = em.indexOf('.') > 0;
// Check 3 - ensures there's always something after a @ or dot
var c3 = !(em.slice(-1)=="@"||em.slice(-1)==".");
return (c1&&c2&&c3); // If all TRUE, great.
},
// Shortcut to quickly check any text input by dom id
checkById : function(inputId){
d = document.getElementById(inputId);
return d?emailv.check(d.value):false;
},
// Check delay for checking on real-time inputs
checkDelay: function(em){
clearTimeout(emailv.to);
emailv.to = setTimeout("emailv.checkDelayP2('"+em+"')",1000);
},
// Part two of Check delay
checkDelayP2: function(em){
if(emailv.check(em)){ // Javascript filter says it seems okay
// For sakes of this demo, pretend we are now making a background
// check to see if e-mail is taken. We tell the user to wait..
emailv.status("Wait..");
// Pretend the background check took 2 seconds
// and said e-mail was available
setTimeout("emailv.status('OK')",2000);
} else {
// Javascript say it's bad, mmmkay?
emailv.status("BAD E-mail");
}
},
status : function(s){
document.getElementById('emailstatus').innerHTML=s;
}
}
<h2>1 of 2 - Delayed check</h2>
<ul>
<li><strong>Waits until the user has stopped typing</strong></li>
<li>Useful for when you want to then send e-mail to background database to check if it exists.</li>
<li>Allows them 1 idle second before checking the e-mail address.</li>
</ul>
<input type="text" size="50" id="youremail" name="youremail" onkeyup="emailv.checkDelay(this.value)" onpaste="emailv.checkDelay(this.value)" />
<span id='emailstatus'></span>
<h2>2 of 2 - Instant Check</h2>
<input type="text" size="50" id="youremail2" name="youremail2" />
<a href="Javascript:void(0)" onclick="alert(emailv.checkById('youremail2')?'Seems okay to me':'This e-mail is dodgy')">Check e-mail</a>
It would be better to avoid stopping the user entering a valid e-mail than to apply so many restrictions that it becomes complicated.
This is just my opinion!
Upvotes: 5
Reputation: 3287
I've slightly modified Jaymon's answer for people who want really simple validation in the form of:
[email protected]
The regular expression:
/^\S+@\S+\.\S+$/
To prevent matching multiple @ signs:
/^[^\s@]+@[^\s@]+\.[^\s@]+$/
The above regexes match the whole string, remove the leading and ^
and trailing $
if you want to match anywhere in the string. The example below matches anywhere in the string.
If you do want to match the whole sring, you may want to trim()
the string first.
Example JavaScript function:
function validateEmail(email) {
var re = /\S+@\S+\.\S+/;
return re.test(email);
}
console.log(validateEmail('my email is [email protected]')); // true
console.log(validateEmail('my email is anystring@anystring .any')); // false
Upvotes: 1371
Reputation: 1487
Wikipedia standard mail syntax :
https://en.wikipedia.org/wiki/Email_address#Examples https://fr.wikipedia.org/wiki/Adresse_%C3%A9lectronique#Syntaxe_exacte
Function :
function validMail(mail)
{
return /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()\.,;\s@\"]+\.{0,1})+([^<>()\.,;:\s@\"]{2,}|[\d\.]+))$/.test(mail);
}
Valid emails :
validMail('[email protected]') // Return true
validMail('[email protected].') // Return true
validMail('[email protected]') // Return true
validMail('user@localserver') // Return true
validMail('[email protected]') // Return true
validMail('user+mailbox/[email protected]') // Return true
validMail('"very.(),:;<>[]\".VERY.\"very@\\ \"very\".unusual"@strange.example.com') // Return true
validMail('!#$%&\'*+-/=?^_`.{|}[email protected]') // Return true
validMail('"()<>[]:,;@\\\"!#$%&\'-/=?^_`{}| ~.a"@example.org') // Return true
validMail('"Abc@def"@example.com') // Return true
validMail('"Fred Bloggs"@example.com') // Return true
validMail('"Joe.\\Blow"@example.com') // Return true
validMail('Loïc.Accentué@voilà.fr') // Return true
validMail('" "@example.org') // Return true
validMail('user@[IPv6:2001:DB8::1]') // Return true
Invalid emails :
validMail('Abc.example.com') // Return false
validMail('A@b@[email protected]') // Return false
validMail('a"b(c)d,e:f;g<h>i[j\k][email protected]') // Return false
validMail('just"not"[email protected]') // Return false
validMail('this is"not\[email protected]') // Return false
validMail('this\ still\"not\\[email protected]') // Return false
validMail('[email protected]') // Return false
validMail('[email protected]') // Return false
Show this test : https://regex101.com/r/LHJ9gU/1
Upvotes: 33
Reputation: 36
Regex updated! try this
let val = '[email protected]';
if(/^[a-z0-9][a-z0-9-_\.]+@([a-z]|[a-z0-9]?[a-z0-9-]+[a-z0-9])\.[a-z0-9]{2,10}(?:\.[a-z]{2,10})?$/.test(val)) {
console.log('passed');
}
typscript version complete
//
export const emailValid = (val:string):boolean => /^[a-z0-9][a-z0-9-_\.]+@([a-z]|[a-z0-9]?[a-z0-9-]+[a-z0-9])\.[a-z0-9]{2,10}(?:\.[a-z]{2,10})?$/.test(val);
more info https://git.io/vhEfc
Upvotes: 30
Reputation: 23208
HTML5 itself has email validation. If your browser supports HTML5 then you can use the following code.
<form>
<label>Email Address
<input type="email" placeholder="[email protected]" required>
</label>
<input type="submit">
</form>
jsFiddle link
From the HTML5 spec:
A valid e-mail address is a string that matches the
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.!#$%&'*+\/=?^_`{|}~-]+@[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])?)*$/
Upvotes: 330
Reputation: 2522
In my case, I wanted to avoid ~
and #
that's why I have used another solution:
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]',
'pio_pio@#factory.com',
'[email protected]#om',
'[email protected]*om',
'pio^[email protected]'
]
for(const email of emails){
document.write(email+' : '+validEmail(email)+'</br>');
}
Upvotes: 11
Reputation: 137722
All email addresses contain an 'at' (i.e. @) symbol. Test that necessary condition:
email.includes('@')
Or, if you need to support IE/older browsers:
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.
Upvotes: 93
Reputation: 5738
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:
^\S+@\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.
EDIT: We can also check for '.' in the email using
/^\S+@\S+\.\S+$/
Upvotes: 538
Reputation: 1808
var testresults
function checkemail() {
var str = document.validation.emailcheck.value
var filter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
if (filter.test(str))
testresults = true
else {
alert("Please input a valid email address!")
testresults = false
}
return (testresults)
}
function checkbae() {
if (document.layers || document.getElementById || document.all)
return checkemail()
else
return true
}
<form name="validation" onSubmit="return checkbae()">
Please input a valid email address:<br />
<input type="text" size=18 name="emailcheck">
<input type="submit" value="Submit">
</form>
Upvotes: 15
Reputation: 13465
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])?)$
It's based on RFC 2822
Test it at https://regex101.com/r/857lzc/1
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.
Note 2: The beginning of an email (before the @ sign) can be case sensitive (via the spec). However, anyone with a case-sensitive email is probably used to having issues, and, in practice, case insensitive is a safe assumption. More info: Are email addresses case sensitive?
More info: http://www.regular-expressions.info/email.html
Upvotes: 75
Reputation: 1818
Most of the answers here are not linter friendly, it's a mess! Some of them are also outdated!
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
Upvotes: 9
Reputation: 924
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})[^\s@]+@[^\s@]+\.[^\s@]+[a-z0-9]$/
Please let me know if this solution works for you. Thanks.
Upvotes: 4
Reputation: 2202
Wow, there are a lot of answers that contain slightly different regular expressions. I've tried 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 @.
Upvotes: 11
Reputation: 1221
// Try this regular Expression by ES6 function
const emailValidate = (email) => {
const regexp= /^[\w.%+-]+@[\w.-]+\.[\w]{2,6}$/;
return regexp.test(email);
}
Upvotes: 1
Reputation: 9436
Yet another perfect regexp for email validation
/^([^\s\@])+\@(([^\s\@\.])+\.)+([^\s\.]{2,})+$/
You can test it here https://regex101.com/r/FV3pUI/2
Upvotes: 2
Reputation: 1481
You can use this regex (from w3resource (*not related to W3C)):
/^\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.
Upvotes: 4
Reputation: 868
// Html form call function name at submit button
<form name="form1" action="#">
<input type='text' name='text1'/>
<input type="submit" name="submit" value="Submit"
onclick="ValidateEmail(document.form1.text1)"/>
</from>
// Write the function name ValidateEmail below
<script>
function ValidateEmail(inputText)
{
var mailformat = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
if(inputText.value.match(mailformat))
{
alert("Valid email address!");
document.form1.text1.focus();
return true;
}
else
{
alert("You have entered an invalid email address!");
document.form1.text1.focus();
return false;
}
}
</script>
Upvotes: 1
Reputation: 3979
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
);
};
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.
Upvotes: 9
Reputation: 800
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
Upvotes: 1
Reputation: 529
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 /^(([^<>()\[\]\\.,;:\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,}))$/;
}
/**
* @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}.`);
Upvotes: 0
Reputation: 203
General email regex (RFC 5322 Official Standard): https://emailregex.com/
JavaScript:
/^(([^<>()\[\]\\.,;:\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,}))$/
Upvotes: 2
Reputation: 7048
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('nz@co.'); // 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.
Upvotes: 1
Reputation: 1149
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])+
Upvotes: 12
Reputation: 9024
I am using this function
/**
* @param {*} email
*/
export const validateEmail = email => {
return new RegExp(/[\w-]+@([\w-]+\.)+[\w-]+/gm).test(email);
};
Upvotes: 0
Reputation: 3207
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>
Upvotes: 1
Reputation: 23592
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.!#$%&'*+\/=?^_`{|}~-]+@[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
Upvotes: 3
Reputation: 2279
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.
Upvotes: 87
Reputation: 2394
I was looking for a Regex in JS that passes all Email Address test cases:
[email protected]
Valid email
[email protected]
Email contains dot in the address field
[email protected]
Email contains dot with subdomain
[email protected]
Plus sign is considered valid character
[email protected]
Domain is valid IP address
email@[192.0.2.123]
Square bracket around IP address is considered valid
“email”@example.com
Quotes around email is considered valid
[email protected]
Digits in address are valid
[email protected]
Dash in domain name is valid
[email protected]
Underscore in the address field is valid
[email protected]
.name
is valid Top Level Domain name
[email protected]
Dot in Top Level Domain name also considered valid (using co.jp
as example here)
[email protected]
Dash in address field is valid
Here we go :
OR regex:
Regex = /(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@[*[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+]*/
Upvotes: 10