开发者

improve my jquery validation plugin code

开发者 https://www.devze.com 2022-12-31 04:00 出处:网络
Just hoping soemone can help me to write better code 开发者_运维百科than I can come up with on my own.

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


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.


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']);
   }
  }
 }
});


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

精彩评论

暂无评论...
验证码 换一张
取 消