Home > Blockchain >  jQuery validation multiple equals
jQuery validation multiple equals

Time:07-22

I am using the jQuery validation tool https://jqueryvalidation.org/

And trying to validate a field for the value of either "green", "Green" or "GREEN". Can you add multiple equals values to the rules? Or may be it is better to convert the string to lowercase?

 $.validator.addMethod("equals", function(value, element, string) {
 return value === string;
 }, $.validator.format("Please answer the question"));


 $("#contactForm").validate({
   rules: {
      question: {
        required: true,
        equals: "green"  
      } 
    }   
 });

CodePudding user response:

You can define a validation method that takes an array of values to allow.

$.validator.addMethod("member", function(value, element, array) {
  return array.includes(value);
}, $.validator.format("Please answer the question"));

$("#contactForm").validate({
   rules: {
      question: {
        required: true,
        member: ["green", "GREEN", "Green"]
      } 
    }   
 });

Another alternative is to use one of the regexp methods here: jQuery validate: How to add a rule for regular expression validation?

Then you can use alternatives in the regexp:

regex: /green|Green|GREEN/

With a regular expression you can also make it case-insensitive easily:

regex: /green/i
  • Related