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"  
      } 
    }   
 });
1
  • Do you really need multiple equals, or just case-insensitive matching? Commented Jul 21, 2022 at 14:50

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

4 Comments

I tried this previously equals ["green", "GREEN", "Green"] And it then just accepted none of them?
A string can never be equal to an array.
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.
Sorry, I had the parameters wrong, try it now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.