I am seeing a lot of help writing custom jQuery validation for any type of field on my page, but how would I write a custom validation method that takes values from multiple fields into account (cross-filed validation)? I think I’m supposed to do $.validator.addMethod to add my custom method and then add a rule to the validator object (instead of to a specific field), but I am having trouble with the syntax. Can anyone help?
For example,
I have two fields: date and time. My form is valid only if:
- Both are filled
- The date is not a sunday
- The time is between 6am and 6pm
You do need some custom rules here, but each validation method doesn’t need to take multiple fields into account. Seems to me, you need three different rules: required applied to both fields (already built in) and then a custom rule for the time rule (6AM – 6PM) and the day rule (can’t be a Sunday):
Example: http://jsfiddle.net/andrewwhitaker/7KFgn/
Note that the example uses DateJS to make parsing the dates easier.