How can I allow only gmail.com as domain in my email field validating using jquery-validation plugin?

前端 未结 3 1879
清歌不尽
清歌不尽 2020-12-12 05:27

How can I allow only gmail.com as domain in my email field validating using jquery-validation plugin ?

$(\"#myForm\").validate({
rules: {
    myemail: {
             


        
相关标签:
3条回答
  • 2020-12-12 06:02

    Take the Gmail regex from this answer and use it within the addMethod method to create a new custom rule called "gmail"...

    jQuery.validator.addMethod('gmail', function (value, element) {
        return this.optional(element) || /^[a-z0-9](\.?[a-z0-9]){5,}@gmail\.com$/i.test(value);
    }, "not a valid Gmail email address");
    
    $("#myForm").validate({
        rules: {
            myemail: {
                required: true,
                gmail: true
            }
        }
    });
    

    It does not matter if you call .validate() before or after the .addMethod() method.

    DEMO: http://jsfiddle.net/fPFpF/

    0 讨论(0)
  • 2020-12-12 06:20

    You can accept gmail like this below, notice I added in for it to ignore .org and .net as well you can keep tweaking your regex to exactly how you want it.

    \w*\@(?!org)(?!net)[g][m][a][i][l]
    

    Edit based on Sparky's : CASE -- Uppercase and 3 letter email name @gmail.com

    $(document).ready(function () {
    
    jQuery.validator.addMethod('gmail', function (value, element) {
        return this.optional(element) || /^[a-z0-9](\.?[a-z0-9]){3,}@[Gg][Mm][Aa][Ii][Ll]\.com$/i.test(value);
    }, "not a valid Gmail email address");
    
    $('#myform').validate({
        rules: {
            field1: {
                required: true,
                gmail: true
            }
        },
        submitHandler: function (form) { // for demo
            alert('valid form');
            return false;
        }
    });
    
    });
    
    0 讨论(0)
  • 2020-12-12 06:24

    You have to write a regular expression that accepts strings ending with 'gmail.com'

    Check here for regex on Gmail address:

    Regular Expression - Validate Gmail addresses

    Check here on how to add regexp validation:

    jQuery validate: How to add a rule for regular expression validation?

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