0

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

$("#myForm").validate({
rules: {
    myemail: {
        required: true,
        email: true,
    }
}
});
babtech
  • 159
  • 3
  • 5
  • 12

3 Answers3

1

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;
    }
});

});
Tom Stickel
  • 19,633
  • 6
  • 111
  • 113
1

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/

Community
  • 1
  • 1
Sparky
  • 98,165
  • 25
  • 199
  • 285
-1

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?

Community
  • 1
  • 1
Ulugbek
  • 164
  • 1
  • 8