Email validation using jQuery

后端 未结 30 1880
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 16:52

I\'m new to jQuery and was wondering how to use it to validate email addresses.

相关标签:
30条回答
  • 2020-11-22 17:24
    • http://so.devilmaycode.it/jquery-validate-e-mail-address-regex/
    • using new regex
    • added support for Address tags (+ sign)

    function isValidEmailAddress(emailAddress) {
        var pattern = /^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")@(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i;
        return pattern.test(emailAddress);
    };

    if( !isValidEmailAddress( emailaddress ) ) { /* do stuff here (email is invalid) */ }
    

    this was provided by user Luca Filosofi in this answer this answer

    0 讨论(0)
  • 2020-11-22 17:25

    I would use the jQuery validation plugin for a few reasons.

    You validated, ok great, now what? You need to display the error, handle erasing it when it is valid, displaying how many errors total perhaps? There are lots of things it can handle for you, no need to re-invent the wheel.

    Also, another huge benefit is it's hosted on a CDN, the current version at the time of this answer can be found here: http://www.asp.net/ajaxLibrary/CDNjQueryValidate16.ashx This means faster load times for the client.

    0 讨论(0)
  • 2020-11-22 17:26

    You can use jQuery Validation and, in a single HTML line, you can validate the email and the email validation message: type="email" required data-msg-email="Enter a valid email account!"

    You can use the data-msg-email parameter to place a personalized message or otherwise do not place this parameter and the default message will be displayed: "Please enter a valid email address."

    Full example:

    <form class="cmxform" id="commentForm" method="get" action="">
      <fieldset>
        <p>
          <label for="cemail">E-Mail (required)</label>
          <input id="cemail" type="email" name="email" required data-msg-email="Enter a valid email account!">
        </p>
        <p>
          <input class="submit" type="submit" value="Submit">
        </p>
      </fieldset>
    </form>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/jquery-validation@1.17.0/dist/jquery.validate.js"></script>
    <script>
    $("#commentForm").validate();
    </script>
    
    0 讨论(0)
  • 2020-11-22 17:27

    This question is more dificult to answer than seems at first sight. If you want to deal with emails correctly.

    There were loads of people around the world looking for "the regex to rule them all" but the truth is that there are tones of email providers.

    What's the problem? Well, "a_z%@gmail.com cannot exists but it may exists an address like that through another provider "a__z@provider.com.

    Why? According to the RFC: https://en.wikipedia.org/wiki/Email_address#RFC_specification.

    I'll take an excerpt to facilitate the lecture:

    The local-part of the email address may use any of these ASCII characters:
    
    - uppercase and lowercase Latin letters A to Z and a to z;
    - digits 0 to 9;
    - special characters !#$%&'*+-/=?^_`{|}~;
    - dot ., provided that it is not the first or last character unless quoted, and provided also that it does not appear consecutively unless quoted (e.g. John..Doe@example.com is not allowed but "John..Doe"@example.com is allowed);[6]
    Note that some mail servers wildcard local parts, typically the characters following a plus and less often the characters following a minus, so fred+bah@domain and fred+foo@domain might end up in the same inbox as fred+@domain or even as fred@domain. This can be useful for tagging emails for sorting, see below, and for spam control. Braces { and } are also used in that fashion, although less often.
    - space and "(),:;<>@[\] characters are allowed with restrictions (they are only allowed inside a quoted string, as described in the paragraph below, and in addition, a backslash or double-quote must be preceded by a backslash);
    - comments are allowed with parentheses at either end of the local-part; e.g. john.smith(comment)@example.com and (comment)john.smith@example.com are both equivalent to john.smith@example.com.
    

    So, i can own an email address like that:

    A__z/J0hn.sm{it!}h_comment@example.com.co
    

    If you try this address i bet it will fail in all or the major part of regex posted all across the net. But remember this address follows the RFC rules so it's fair valid.

    Imagine my frustration at not being able to register anywhere checked with those regex!!

    The only one who really can validate an email address is the provider of the email address.

    How to deal with, so?

    It doesn't matter if a user adds a non-valid e-mail in almost all cases. You can rely on HTML 5 input type="email" that is running near to RFC, little chance to fail. HTML5 input type="email" info: https://www.w3.org/TR/2012/WD-html-markup-20121011/input.email.html

    For example, this is an RFC valid email:

    "very.(),:;<>[]\".VERY.\"very@\\ \"very\".unusual"@strange.example.com
    

    But the html5 validation will tell you that the text before @ must not contain " or () chars for example, which is actually incorrect.

    Anyway, 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.

    A good practice while doing this is the "enter your e-mail again" input to avoid user typing errors. If this is not enough for you, add a pre-submit modal-window with a title "is this your current e-mail?", then the mail entered by the user inside an h2 tag, you know, to show clearly which e-mail they entered, then a "yes, submit" button.

    0 讨论(0)
  • 2020-11-22 17:28

    A very simple solution is to use html5 validation:

    <form>
      <input type="email" required pattern="[^@]+@[^@]+\.[a-zA-Z]{2,6}">
    
      <input type="submit">
    </form>
    

    http://jsfiddle.net/du676/56/

    0 讨论(0)
  • 2020-11-22 17:30

    I would recommend Verimail.js, it also has a JQuery plugin.

    Why? Verimail supports the following:

    • Syntax validation (according to RFC 822)
    • IANA TLD validation
    • Spelling suggestion for the most common TLDs and email domains
    • Deny temporary email account domains such as mailinator.com

    So besides validation, Verimail.js also gives you suggestions. So if you type an email with the wrong TLD or domain that is very similar to a common email domain (hotmail.com, gmail.com, etc), it can detect this and suggest a correction.

    Examples:

    • test@gnail.con -> Did you mean test@gmail.com?
    • test@hey.nwt -> Did you mean test@hey.net?
    • test@hottmail.com -> Did you mean test@hotmail.com?

    And so on..

    To use it with jQuery, just include verimail.jquery.js on your site and run the function below:

    $("input#email-address").verimail({
        messageElement: "p#status-message"
    });
    

    The message element is an element in which a message will be shown. This can be everything from "Your email is invalid" to "Did you mean ...?".

    If you have a form and want to restrict it so that it cannot be submitted unless the email is valid, then you can check the status using the getVerimailStatus-function as shown below:

    if($("input#email-address").getVerimailStatus() < 0){
        // Invalid
    }else{
        // Valid
    }
    

    This function returns an integer status code according to the object Comfirm.AlphaMail.Verimail.Status. But the general rule of thumb is that any codes below 0 is codes indicating errors.

    0 讨论(0)
提交回复
热议问题