Forcing a text field to be a valid email?

This question already has an answer here:

  • How to validate an email address in JavaScript? 68 answers

  • Support only newer browsers? Try this:

    <input type="email" name="emailaddress">
    

    Note that support is somewhat limited, but it might work for you if it falls into these browsers:

    http://caniuse.com/#feat=forms

    On a related note:

    Validate email address in JavaScript?


    function IsEmail(email) {
        var regex = /^([a-zA-Z0-9_.+-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
        return regex.test(email);
    }
    

    You can use the answer @Mike Robinson gave along with some simple validation (found here) as a fallback for older browsers:

    HTML:

    <input type="email" name="emailaddress" id="valid_email"><div class="validate">Please enter a valid email!</div>
    

    JS:

    $('.validate').hide();
    $('body').on('blur', '#valid_email', function() {
        $('.validate').hide();
        if(!isValidEmailAddress($(this).val())) {
           $('.validate').show();
        }
    });
    
    function isValidEmailAddress(emailAddress) {
        var pattern = new RegExp(/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:.[a-zA-Z0-9-]+)*$/i);
        return pattern.test(emailAddress);
    };
    

    Fiddle

    Or, even simpler, you can just use the jQuery Validation Plugin.

    You'll also want to validate on the backend, you can do this with PHP filters:

    if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
        // do something if email is valid
    }
    
    链接地址: http://www.djcxy.com/p/16504.html

    上一篇: jquery有效的电子邮件检查

    下一篇: 强制一个文本字段是一个有效的电子邮件?