Using the jQuery Validation plugin to validate forms, how would you confirm that a string is exactly X characters long?
+4
A:
Since there is (currently) no built-in method for this, you'd need to add your own method. This would work:
jQuery.validator.addMethod("exactlength", function(value, element, param) {
return this.optional(element) || value.length == param;
}, jQuery.format("Please enter exactly {0} characters."));
Which could then be used like this:
$("#formtovalidate").validate({
rules: {
somefield: {
exactlength: 10
}
});
Update - How it Works
I've been asked how this works. I don't know all the details; I modeled this method on previously existing ones. However, this is my best attempt to explain it.
- The function takes in
value
,element
, andparam
.value
is the value entered in the field being validatedelement
is the field itselfparam
is whatever comes after the rule type and colon. In the example above, it's the 10 inexactlength: 10
- The next line is a
return
statement. This will give the final verdict of the validation method back to the code that called it. Any validation method that returnstrue
is saying 'this field passes validation!' It will return the value of the line it's on. - The
return
is followed by two declarations, separated by an 'or' operator (||
).- The
||
operator means 'evaluate the item left of this. If it's true, return true. If not, try the one on the right. If it's true, return true. Otherwise, return false.'- The item on the left is
this.optional(element)
. If the element is not required in your rules, this will return true, and so will the validation. Which means 'If I don't tell you that this field is required, I don't care whether it validates.' - If the field is required, we move to the right side of the
||
. This is the actual validation test. It compares the length of the field's input with the length you specified it should be. If they are the same, it returns true, the method returns true, and validation passes. Otherwise, validation fails.
- The item on the left is
- The
That's about it. For further help, see the documentation, particularly the part about custom validation methods.
Nathan Long
2009-08-04 18:32:03
I ran into this problem and wanted to leave some help for the next person. :)
Nathan Long
2009-08-04 18:32:24
Probably wise to mark this one as answered? (even if you did answer it yourself :P)
Jason Berry
2009-08-05 07:08:59
I have to wait a certain time period before I can accept my own answer - right now it says 26 hours.
Nathan Long
2009-08-05 15:48:37
How does it work? Like what is element and param? I am not sure what this.optional(element) does either?Thanks by the way it is what I needed.
chobo2
2009-08-20 19:56:43
@chobo2 - see my new explanation above.
Nathan Long
2009-08-21 15:25:07