jQuery Validation using the class instead of the name value

JavascriptJqueryHtmlCssJquery Validate

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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.

Solution 3 - Javascript

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.

Solution 4 - Javascript

Here's the solution using jQuery:

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

Solution 5 - Javascript

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>

Solution 6 - Javascript

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

Solution 7 - Javascript

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--;
    }
}

Solution 8 - Javascript

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.

Solution 9 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMattView Question on Stackoverflow
Solution 1 - JavascriptNick CraverView Answer on Stackoverflow
Solution 2 - JavascriptRicardoSView Answer on Stackoverflow
Solution 3 - JavascriptNimeshka SrimalView Answer on Stackoverflow
Solution 4 - JavascriptAjay SharmaView Answer on Stackoverflow
Solution 5 - JavascriptDelan AzabaniView Answer on Stackoverflow
Solution 6 - JavascriptFarzherView Answer on Stackoverflow
Solution 7 - JavascriptBarnoView Answer on Stackoverflow
Solution 8 - JavascriptGabriel StarlingView Answer on Stackoverflow
Solution 9 - JavascriptMehran AhmadifarView Answer on Stackoverflow