Combining validation methods in a jQuery validation plugin using "or" instead of "and"

The jQuery plugin checks there are several methods that do the same thing but in different locales, for example dateISO, and dateDEboth check the date formatting. How to combine them so that the input element accepts either?

Let's say I have <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 several different date formats - for example, the user should be able to enter either an ISO date or a date formatted in accordance with 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 this requirement will never be fulfilled. Is there a way to combine them as an “or,” and not as an “and,” without having to write my own verification method?

And if I need to write my own, how can I make this as general as possible?

+2
source share
2 answers

While you can combine regular expressions such as Reigel, you can also just call these methods directly (if they change!), For example:

$.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");

date dateDE , dateDE . , date. , , dateDE.


: :

$.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");

:

$("form").validate({
  rules: {
    dateFieldName: { oneOf: { dateISO:true, date:true } }
  }
});

, , true .

+5
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);
}

...:)

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");
0

All Articles