Jquery: form validation
i'm using jquery validation plugin and i'attempting to define a rule for the only field of form: The value of the field must contain a string of five numbers( the field value will always contain letters ). I've try with the rule required( dependency-callback ) and got something like that:
rules: {
field: {
required: function(element) {
var value_field = $('#field').attr('value');
}
}
}
Now i need to search value_field for a string of five numbers. Am i using the good rule 开发者_如何学Cfor this case? And how to search for the needed string?
thanks
You need to add a custom method to the validator before you setup the validator with your rules:
$.validator.addMethod("FiveDigits", function(value, element) {
return this.optional(element) || /^\d{5}$/.test(value);
}, "A 5 digit number please");
then use the following rule :
fieldName : { required : true, FiveDigits: true }
// define variables
var field_value, regexp;
// set field_value to #field's value
field_value = $("field").val();
// the regular expression that matches the pattern we're looking for
regexp = /\d{5}/;
if (field_value.match(regexp)) {
// do something
} else {
// do something else
}
精彩评论