I have jQuery Validation plugin on a page. When someone types the phone number into the form field, I want the validator to only recognize a certain format:
###-
Simply use the phoneUS
rule included in the jQuery Validate plugin's additional-methods.js file.
DEMO: http://jsfiddle.net/c9zy9/
$(document).ready(function () {
$('#myform').validate({ // initialize the plugin
rules: {
phone_number: {
required: true,
phoneUS: true
}
}
});
});
Alternatively, instead of including the entire additional-methods.js
file, you can just pull out the phoneUS
method.
DEMO: http://jsfiddle.net/dSz5j/
$(document).ready(function () {
jQuery.validator.addMethod("phoneUS", function (phone_number, element) {
phone_number = phone_number.replace(/\s+/g, "");
return this.optional(element) || phone_number.length > 9 && phone_number.match(/^(\+?1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, "Please specify a valid phone number");
$('#myform').validate({ // initialize the plugin
rules: {
phone_number: {
required: true,
phoneUS: true
}
}
});
});