0

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"  
      } 
    }   
 });
j00m
  • 491
  • 5
  • 20

1 Answers1

1

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
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • I tried this previously equals ["green", "GREEN", "Green"] And it then just accepted none of them? – j00m Jul 21 '22 at 15:13
  • A string can never be equal to an array. – Barmar Jul 21 '22 at 15:14
  • This is the error I get when I try your exact code: Uncaught TypeError: elements.includes is not a function. Exception occurred when checking element question, check the 'member' method. – j00m Jul 21 '22 at 15:16
  • Sorry, I had the parameters wrong, try it now. – Barmar Jul 21 '22 at 15:18