Reputation: 2383
I'm using the jQuery Validate plugin and want to validate an input field using a fixed amount of numbers with a dash in the middle like so: XXXXXX-XXXX. I know how to validate numbers but how can I get the plugin to validate this specific format?!
Thanks!
Upvotes: 1
Views: 9187
Reputation: 1038710
You could use a regex. Add a custom validator method as illustrated here:
$.validator.addMethod(
"regex",
function(value, element, regexp) {
var re = new RegExp(regexp);
return re.test(value);
},
"Please check your input."
);
And then attach it to the input element that you need to validate:
$('#id_of_textbox').rules('add', { regex: '^[0-9]{6}-[0-9]{4}$' })
or if you are using it with the form:
$('#id_of_form').validate({
rules: {
name_of_textbox: {
regex: '^[0-9]{6}-[0-9]{4}$'
}
},
messages: {
name_of_textbox: {
regex: 'Please provide a valid input for this field'
}
}
});
And here's a live demo.
Upvotes: 6
Reputation: 5977
You can do Regest with Javascript as basic as that.. same way you can include the regest with jquery plugin as well.
Upvotes: 1