问题
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?
回答1:
While you can combine the regexes like Reigel has, you can also just call those methods directly (in case they change!), like this:
$.validator.addMethod("dateISODE", function(value, element) {
return $.validator.methods.dateISO.apply(this, arguments)
|| $.validator.methods.date.apply(this, arguments);
}, "Please enter a valid ISO or German date");
Now I have date instead of dateDE here, because in newer versions of the plugin dateDE was removed. It's now in a localization file that just overrides the date method. If you're using an older version that's fine, just stick with dateDE.
You can try a demo here
Update for comments: A more generic form would look like this:
$.validator.addMethod("oneOf", function(value, element, params) {
for(p in params) {
if(params.hasOwnProperty(p) &&
$.validator.methods[p].apply(this, [value, element, params[p]]))
return true;
}
return false;
}, "Please enter a valid date");
The rules would look like this:
$("form").validate({
rules: {
dateFieldName: { oneOf: { dateISO:true, date:true } }
}
});
You can try a demo here, this takes any number of validator functions and runs them, at least one must return true for it to succeed.
回答2:
dateISO: function(value, element) {
return this.optional(element) || /^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(value);
},
dateDE: function(value, element) {
return this.optional(element) || /^\d\d?\.\d\d?\.\d\d\d?\d?$/.test(value);
}
source
lets combine it... :)
jQuery.validator.addMethod("dateISOorDE", function(value, element) {
return this.optional(element) || /^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(value) || /^\d\d?\.\d\d?\.\d\d\d?\d?$/.test(value);
}, "Please specify the correct date");
来源:https://stackoverflow.com/questions/3138646/combining-validation-methods-in-jquery-validation-plugin-with-or-instead-of-a