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,
}
}
});
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,
}
}
});
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;
}
});
});
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.
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?