0

Just hoping soemone can help me to write better code than I can come up with on my own.

I am using the jquery validation plugin. I have some fields that are mandatory ONLY if certain options are chosen.

The below code works fine. But the thing is, is that that my list of 'OR's is much longer than I've put here. and it needs to be applied not just to 'directorsName' but a whole long list of inputs, selects etc.

My question is.. how can I wrap up the code contained inside the RETURN? (so I dont have to keep repeating my 'OR's. I'm guessign I need a function but I'm unsure of the syntax)

$("#myForm").validate({
 rules: {
  directorsName : { 
   required: function(element) {
   return ( $('#account_for').val() == "Joint" || $('#directors_number').val() == "2" || $('#directors_number').val() == "3" );
   }
  }
 }
});

Thanks in advance

3 Answers 3

1

Here's a code snippet for a custom validator. You can apply this same syntax to your own custom validation needs.

$.validator.addMethod("noanon", function(value) {
          return value.toLowerCase().indexOf("anonymous") != 0;
      }, 'Do not hide behind the cover of anonymity')

You can then use it just like any of the built-in validation rules like:

name: {
       required: true,
       minlength: 2,
       noanon: true
  },

If you have not already read it, I suggest reading the 3-part blog that this code comes from over at coldFusion Jedi.

Sign up to request clarification or add additional context in comments.

Comments

1

You can do this, which is supported cross browser using $.inArray():

$("#myForm").validate({
 rules: {
  directorsName : { 
   required: function(element) {
     return $('#account_for').val() == "Joint" || 
            $.inArray($('#directors_number').val(), ['2','3']);
   }
  }
 }
});

Comments

0
list = ['1', '2', '3', '...'];
return $('#account_for').val() == "Joint" || list.indexOf($('#directors_number').val()) != -1;

1 Comment

Note that the Array.prototype.indexOf method is not supported by IE, however an implementation of the method can be included to support it.

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.