Access our premium support and let us know your problems, we will help you solve them.

0
No products in the cart.
  • This topic is empty.
Viewing 15 posts - 1 through 15 (of 31 total)
  • Author
    Posts
  • #8968
    blankDavid Hoang
    Keymaster

    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?

    #8997
    blankDavid Hoang
    Keymaster

    If 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
    
    #8998
    blankDavid 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;
        }
        }
    
    #8969
    blankDavid Hoang
    Keymaster

    One 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, '');
        };
    }
    
    #8975
    blankDavid Hoang
    Keymaster

    If you are using AngularJS, just add type="email" to the input element:

    https://docs.angularjs.org/api/ng/input/input%5Bemail%5D

    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');
    } 
    
    #8976
    blankDavid Hoang
    Keymaster

    I 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');
                }
            });
    }
    
    #8987
    blankDavid Hoang
    Keymaster

    Following 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;
          }
      }
      
    #8970
    blankDavid 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
    
    #8977
    blankDavid Hoang
    Keymaster

    If 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"});
    
    #8988
    blankDavid Hoang
    Keymaster

    Whoever 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);
    }
    
    #8989
    blankDavid Hoang
    Keymaster

    In 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 
    
    #8971
    blankDavid Hoang
    Keymaster

    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}$/; 
    
    #8990
    blankDavid Hoang
    Keymaster

    There 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.

    #8978
    blankDavid Hoang
    Keymaster

    I’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.

    #8991
    blankDavid Hoang
    Keymaster

    How 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
    
Viewing 15 posts - 1 through 15 (of 31 total)
  • You must be logged in to reply to this topic.