- This topic is empty.
- AuthorPosts
-
September 5, 2008 at 11:10 am #8968
David Hoang
KeymasterI’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?
September 10, 2013 at 7:37 am #8997David Hoang
KeymasterIf you’re using Closure you can use the built-in
goog.format.EmailAddress
type:http://docs.closure-library.googlecode.com/git/class_goog_format_EmailAddress.html
For example:
goog.format.EmailAddress.isValidAddrSpec("blah@blah.com")
Note that by reading the source (linked above) you can see the comments state that IDN are not supported and that it only aims to cover most addresses:
// This is a fairly naive implementation, but it covers 99% of use cases. // For more details, see http://en.wikipedia.org/wiki/Email_address#Syntax // TODO(mariakhomenko): we should also be handling i18n domain names as per // http://en.wikipedia.org/wiki/Internationalized_domain_name
January 28, 2014 at 12:40 pm #8998David Hoang
Keymaster<pre> **The personal_info part contains the following ASCII characters. 1.Uppercase (A-Z) and lowercase (a-z) English letters. 2.Digits (0-9). 3.Characters ! # $ % & ' * + - / = ? ^ _ ` { | } ~ 4.Character . ( period, dot or fullstop) provided that it is not the first or last character and it will not come one after the other.** </pre> *Example of valid email id* <pre> yoursite@ourearth.com my.ownsite@ourearth.org mysite@you.me.net xxxx@gmail.com xxxxxx@yahoo.com </pre> <pre> xxxx.ourearth.com [@ is not present] xxxx@.com.my [ tld (Top Level domain) can not start with dot "." ] @you.me.net [ No character before @ ] xxxx123@gmail.b [ ".b" is not a valid tld ] xxxx@.org.org [ tld can not start with dot "." ] .xxxx@mysite.org [ an email should not be start with "." ] xxxxx()*@gmail.com [ here the regular expression only allows character, digit, underscore and dash ] xxxx..1234@yahoo.com [double dots are not allowed </pre> **javascript mail code** function ValidateEmail(inputText) { var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/; if(inputText.value.match(mailformat)) { document.form1.text1.focus(); return true; } else { alert("You have entered an invalid email address!"); document.form1.text1.focus(); return false; } }
July 12, 2014 at 1:36 am #8969David Hoang
KeymasterOne of my coworker shared this regex with me. I like it a lot.
function isValidEmailAddress (email) { var validEmail = false; if (email) { email = email.trim().toLowerCase(); var pattern = /^[\w-']+(\.[\w-']+)*@([a-zA-Z0-9]+[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*?\.[a-zA-Z]{2,6}|(\d{1,3}\.){3}\d{1,3})(:\d{4})?$/; validEmail = pattern.exec(email); } return validEmail; } if (typeof String.prototype.trim !== 'function') { String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); }; }
December 15, 2014 at 8:21 am #8975David Hoang
KeymasterIf you are using AngularJS, just add
type="email"
to the input element:In case there is no input element, it can be created dynamically:
var isEmail = $compile('<input ng-model="m" type="email">')($rootScope.$new()). controller('ngModel').$validators["email"]; if (isEmail('email@gmail.com')) { console.log('valid'); }
February 18, 2015 at 3:33 am #8976David Hoang
KeymasterI know its not regex but any way…
This is example with node and npm package email-existence this is ultimate checking if email exist and if its in the right form 🙂
This will ping the email if its responding if it got no response it will return false or else true.
function doesEmailExist(email) { var emailExistence = require('email-existence'); return emailExistence.check(email,function (err,status) { if (status) { return status; } else { throw new Error('Email does not exist'); } }); }
March 2, 2015 at 2:21 am #8987David Hoang
KeymasterFollowing Regex validations:
- No spacial characters before @
- (-) and (.) should not be together after @
- No special characters after @ 2 characters must before @
-
Email length should be less 128 characters
function validateEmail(email) { var chrbeforAt = email.substr(0, email.indexOf('@')); if (!($.trim(email).length > 127)) { if (chrbeforAt.length >= 2) { var re = /^(([^<>()[\]{}'^?\\.,!|//#%*-+=&;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/; return re.test(email); } else { return false; } } else { return false; } }
July 9, 2015 at 3:19 am #8970David Hoang
Keymaster\b[a-z][\w\d_\.]+@\w+\.[a-z]{2}[a-z]?\.?[a-z]{,2}\s
It allows:
abcxyz123@qwert.com abc123xyz@asdf.co.in abc1_xyz1@gmail1.com abc.xyz@gmail.com.in
August 25, 2015 at 9:24 am #8977David Hoang
KeymasterIf you want to use Jquery and want to have modern approach then use JQuery input mask with validation.
http://bseth99.github.io/projects/jquery-ui/5-jquery-masks.html
Demo on how simple jquery input mask is here: http://codepen.io/anon/pen/gpRyBp
Example of simple input mask for date forexample NOT full validation
<input id="date" type="text" placeholder="YYYY-MM-DD"/>
and the script:
$("#date").mask("9999-99-99",{placeholder:"YYYY-MM-DD"});
November 8, 2016 at 4:21 am #8988David Hoang
KeymasterWhoever is using @pvl solution and wants it to pass ESLint Prefer-template then here’s a version where I used template literals instead of string concatenation.
validateEmail(email) { let sQtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]'; let sDtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]'; let sAtom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+'; let sQuotedPair = '\\x5c[\\x00-\\x7f]'; let sDomainLiteral = `\\x5b(${sDtext}|${sQuotedPair})*\\x5d`; let sQuotedString = `\\x22(${sQtext}|${sQuotedPair})*\\x22`; let sDomainRef = sAtom; let sSubDomain = `(${sDomainRef}|${sDomainLiteral})`; let sWord = `(${sAtom}|${sQuotedString})`; let sDomain = `${sSubDomain}(\\x2e${sSubDomain})*`; let sLocalPart = `${sWord}(\\x2e${sWord})*`; let sAddrSpec = `${sLocalPart}\\x40${sDomain}`; // complete RFC822 email address spec let sValidEmail = `^${sAddrSpec}$`; // as whole string let reValidEmail = new RegExp(sValidEmail); return reValidEmail.test(email); }
February 13, 2017 at 1:04 am #8989David Hoang
KeymasterIn nodeJS you can also use validator node module and simply use like that
Install the library with npm install validator
var validator = require('validator'); validator.isEmail('foo@bar.com'); //=> true
March 18, 2017 at 2:57 am #8971David Hoang
KeymasterIf 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}$/;
April 6, 2017 at 11:27 am #8990David Hoang
KeymasterThere are some complex RegEx written here, that also works.
I tested this one and it works too:
[a-zA-Z0-9._]+[@]+[a-zA-Z0-9]+[.]+[a-zA-Z]{2,6}
Please test this here : http://www.regextester.com/?fam=97334
Hope this helps.
June 2, 2017 at 2:52 am #8978David Hoang
KeymasterI’d like to add a short note about non-ASCII characters. Rnevius’s (and co.) solution is brilliant, but it allows to add Cyrillic, Japanese, Emoticons and other unicode symbols which may be restricted by some servers.
The code below will print
true
though it contains UTF-8 characterÐ
.console.log (/^(([^<>()\[\]\\.,;:\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,}))$/.test ('Ð@example.org'))
In my case all non-ASCII symbols are prohibited so I have modified the original expression to exclude all characters above U+007F:
/^(([^\u0080-\uffff<>()\[\]\\.,;:\s@"]+(\.[^\u0080-\uffff<>()\[\]\\.,;:\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,}))$/
Maybe this will help someone to prevent undesired behaviour.
June 17, 2017 at 1:55 am #8991David Hoang
KeymasterHow about creating a function which will test any string against emails’ pattern using regular expression in JavaScript, as we know email addresses can be quite different in different regions, like in UK and Australia it usually ends up with
.co.uk
or.com.au
, so I tried to cover those as well, also check if the string passed to the function, something like this:var isEmail = function(str) { return typeof str==='string' && /^[\w+\d+._]+\@[\w+\d+_+]+\.[\w+\d+._]{2,8}$/.test(str); }
and check if it’s email like below:
isEmail('alex@example.com'); //true isEmail('alireza@test.co.uk'); //true isEmail('peter.example@yahoo.com.au'); //true isEmail('alex@example.com'); //true isEmail('peter_123@news.com'); //true isEmail('hello7___@ca.com.pt'); //true isEmail('example@example.co'); //true isEmail('hallo@example.coassjj#sswzazaaaa'); //false isEmail('hallo2ww22@example....caaaao'); //false
- AuthorPosts
- You must be logged in to reply to this topic.