60

I'd like to validate a form using the jquery validate plugin, but I'm unable to use the 'name' value within the html - as this is a field also used by the server app. Specifically, I need to limit the number of checkboxes checked from a group. (Maximum of 3.) All of the examples I have seen, use the name attribute of each element. What I'd like to do is use the class instead, and then declare a rule for that.

html

This works:

<input class="checkBox" type="checkbox" id="i0000zxthy" name="salutation"  value="1" />

This doesn't work, but is what I'm aiming for:

<input class="checkBox" type="checkbox" id="i0000zxthy" name="i0000zxthy"  value="1" />

javascript:

var validator = $(".formToValidate").validate({    
    rules:{     
    "salutation":{  
             required:true,  
        },  
        "checkBox":{  
             required:true,  
          minlength:3  }  
   }   
});

Is it possible to do this - is there a way of targeting the class instead of the name within the rules options? Or do I have to add a custom method?

Cheers, Matt

Nimeshka Srimal
  • 6,794
  • 5
  • 42
  • 55
Matt
  • 1,121
  • 2
  • 10
  • 16

9 Answers9

88

You can add the rules based on that selector using .rules("add", options), just remove any rules you want class based out of your validate options, and after calling $(".formToValidate").validate({... });, do this:

$(".checkBox").rules("add", { 
  required:true,  
  minlength:3
});
Nick Craver
  • 610,884
  • 134
  • 1,288
  • 1,151
  • 11
    I tried this but it only adds the rule for the first checkbox with class checkBox. Is there something like a .each() enumerator required? – littlegreen May 10 '11 at 14:25
  • 2
    This works though: http://stackoverflow.com/questions/5748346/jquery-validate-plugin-cant-validate-classes – littlegreen May 10 '11 at 14:28
  • 2
    @littlegreen, .each(function() { $(this).rules("add", someOption); }) can work – Allen Nov 09 '13 at 16:56
  • I get only one error message for the same class error fields by this method. Am I missing something or that's the way supposed to be? – Jeaf Gilbert Jun 21 '14 at 18:02
  • Nvm, I missed defining unique names for the elements which is required. Thx though. – Jeaf Gilbert Jun 22 '14 at 07:31
  • Cool. how do I add custom messages though? – Naguib Ihab Jan 30 '15 at 10:24
  • @littlegreen you are correct - Marked answer on this page works only for single input field - and example in link which you posted, works for all input fields. Thanks! P.S (In my use case i worked with input fields and not checkbox-es). – Игор Oct 08 '15 at 12:30
39

Another way you can do it, is using addClassRules. It's specific for classes, while the option using selector and .rules is more a generic way.

Before calling

$(form).validate()

Use like this:

jQuery.validator.addClassRules('myClassName', {
        required: true /*,
        other rules */
    });

Ref: http://docs.jquery.com/Plugins/Validation/Validator/addClassRules#namerules

I prefer this syntax for a case like this.

RicardoS
  • 1,955
  • 1
  • 19
  • 22
  • This is a better solution, though I don't know why you can't pass it through the settings – Dominic Mar 16 '15 at 15:40
  • @RicardoS Does this still work? For some reason I can not get it to function. Is there another method that can do the same thing? –  Oct 02 '20 at 04:59
  • 2
    @saleem I'm really not sure. I haven't used it lately and the answer was 8 years ago. BUT checking their documentation, this is still there: https://jqueryvalidation.org/jQuery.validator.addClassRules/ – RicardoS Oct 02 '20 at 13:36
14

I know this is an old question. But I too needed the same one recently, and I got this question from stackoverflow + another answer from this blog. The answer which was in the blog was more straight forward as it focuses specially for this kind of a validation. Here is how to do it.

$.validator.addClassRules("price", {
     required: true,
     minlength: 2
});

This method does not require you to have validate method above this call.

Hope this will help someone in the future too. Source here.

Nimeshka Srimal
  • 6,794
  • 5
  • 42
  • 55
6

Here's the solution using jQuery:

    $().ready(function () {
        $(".formToValidate").validate();
        $(".checkBox").each(function (item) {
            $(this).rules("add", {
                required: true,
                minlength:3
            });
        });
    });
Ajay Sharma
  • 77
  • 1
  • 1
3

Here's my solution (requires no jQuery... just JavaScript):

function argsToArray(args) {
  var r = []; for (var i = 0; i < args.length; i++)
    r.push(args[i]);
  return r;
}
function bind() {
  var initArgs = argsToArray(arguments);
  var fx =        initArgs.shift();
  var tObj =      initArgs.shift();
  var args =      initArgs;
  return function() {
    return fx.apply(tObj, args.concat(argsToArray(arguments)));
  };
}
var salutation = argsToArray(document.getElementsByClassName('salutation'));
salutation.forEach(function(checkbox) {
  checkbox.addEventListener('change', bind(function(checkbox, salutation) {
    var numChecked = salutation.filter(function(checkbox) { return checkbox.checked; }).length;
    if (numChecked >= 4)
      checkbox.checked = false;
  }, null, checkbox, salutation), false);
});

Put this in a script block at the end of <body> and the snippet will do its magic, limiting the number of checkboxes checked in maximum to three (or whatever number you specify).

Here, I'll even give you a test page (paste it into a file and try it):

<!DOCTYPE html><html><body>
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<script>
    function argsToArray(args) {
      var r = []; for (var i = 0; i < args.length; i++)
        r.push(args[i]);
      return r;
    }
    function bind() {
      var initArgs = argsToArray(arguments);
      var fx =        initArgs.shift();
      var tObj =      initArgs.shift();
      var args =      initArgs;
      return function() {
        return fx.apply(tObj, args.concat(argsToArray(arguments)));
      };
    }
    var salutation = argsToArray(document.getElementsByClassName('salutation'));
    salutation.forEach(function(checkbox) {
      checkbox.addEventListener('change', bind(function(checkbox, salutation) {
        var numChecked = salutation.filter(function(checkbox) { return checkbox.checked; }).length;
        if (numChecked >= 3)
          checkbox.checked = false;
      }, null, checkbox, salutation), false);
    });
</script></body></html>
Delan Azabani
  • 76,631
  • 25
  • 162
  • 208
  • Hi, that's brilliant - thanks for your response Delan, however, the rest of the form (which I haven't shown) uses jQuery as well - so I'd prefer it if I can use jQuery in this example, because it all needs to be validated at the same time. – Matt May 06 '10 at 10:42
1

Since for me, some elements are created on page load, and some are dynamically added by the user; I used this to make sure everything stayed DRY.

On submit, find everything with class x, remove class x, add rule x.

$('#form').on('submit', function(e) {
    $('.alphanumeric_dash').each(function() {
        var $this = $(this);
        $this.removeClass('alphanumeric_dash');
        $(this).rules('add', {
            alphanumeric_dash: true
        });
    });
});
Farzher
  • 12,557
  • 20
  • 61
  • 97
1

If you want add Custom method you can do it

(in this case, at least one checkbox selected)

<input class="checkBox" type="checkbox" id="i0000zxthy" name="i0000zxthy"  value="1" onclick="test($(this))"/>

in Javascript

var tags = 0;

$(document).ready(function() {   

    $.validator.addMethod('arrayminimo', function(value) {
        return tags > 0
    }, 'Selezionare almeno un Opzione');

    $.validator.addClassRules('check_secondario', {
        arrayminimo: true,

    });

    validaFormRichiesta();
});

function validaFormRichiesta() {
    $("#form").validate({
        ......
    });
}

function test(n) {
    if (n.prop("checked")) {
        tags++;
    } else {
        tags--;
    }
}
Barno
  • 3,151
  • 5
  • 27
  • 56
0

If you need to set up multpile class rules you can do it like this:

jQuery.validator.addClassRules({
  name: {
    required: true,
    minlength: 2
  },
  zip: {
    required: true,
    digits: true,
    minlength: 5,
    maxlength: 5
  }
});

source: https://jqueryvalidation.org/jQuery.validator.addClassRules/

Disclaimer: Yes, I know it's 2021 and you shouldn't be using jQuery but, sometimes we have to. This information was really useful to me, so I hope to help some eventual random stranger who has to maintain some legacy system somewhere.

0

$(".ClassName").each(function (item) {
    $(this).rules("add", {
        required: true,
    });
});