The jQuery Validation plugin is one of the most commonly used and useful jQuery plugins. One of the nicest things about it is how easily you can extend it.
I recently had a client ask me to build a form which wouldn’t allow users to sign up with free email addresses– in particular, no Gmail, Yahoo!, or Hotmail accounts. After playing with it for a little bit, I came up with the following jQuery Validation method to check for, and block, Gmail, Yahoo!, and Hotmail (you can easily add other free email providers):
$.validator.addMethod('nofreeemail', function (value) {
return /^([\w-\.]+@(?!gmail.com)(?!yahoo.com)(?!hotmail.com)([\w-]+\.)+[\w-]{2,4})?$/.test(value);
}, 'Free email addresses are not allowed.');
Once you’ve added the method, you can easily call it:
$("#signup_form").validate({
rules: {
'user[first_name]': "required",
'user[last_name]': "required",
'user[title]': "required",
'user[phone]': "required",
'user[email]': {
required: true,
email: true,
nofreeemail: true
}
}
});
So– to wrap up, the final code is:
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$.validator.addMethod('nofreeemail', function (value) {
return /^([\w-\.]+@(?!gmail.com)(?!yahoo.com)(?!hotmail.com)([\w-]+\.)+[\w-]{2,4})?$/.test(value);
}, 'Free email addresses are not allowed.');
$("#signup_form").validate({
rules: {
'user[first_name]': "required",
'user[last_name]': "required",
'user[title]': "required",
'user[phone]': "required",
'user[email]': {
required: true,
email: true,
nofreeemail: true
}
}
});
});
</script>