In the jQuery Validation plugin there are a couple of methods that do the same thing, but for different locales, for example dateISO and dateDE, that both validate date formatting. How do I combine these so that the input element accepts either?
Let’s say I have an <input type="text" name="dateInput" id="dateInput" /> in my form, and I want to allow users to enter only dates in this field. However, I want to allow for several different date formats – for example, the user should be able to enter either an ISO date or a date formatted accoding to German date rules.
If I do
rules: { dateInput: { required: true, dateISO: true, dateDE: true } }
the form will never be valid, as both date formats will be required and that requirement can never be fulfilled. Is there a way to combine these as an “or” instead of as an “and”, without having to write my own validation method?
And if I do have to write my own, how do I make it as generic as possible?
While you can combine the regexes like Reigel has, you can also just call those methods directly (in case they change!), like this:
Now I have
dateinstead ofdateDEhere, because in newer versions of the plugindateDEwas removed. It’s now in a localization file that just overrides thedatemethod. If you’re using an older version that’s fine, just stick withdateDE.You can try a demo here
Update for comments: A more generic form would look like this:
The rules would look like this:
You can try a demo here, this takes any number of validator functions and runs them, at least one must return
truefor it to succeed.