jQuery validate — Require one specific selection which has a particular data attribute

55 Views Asked by At

I am trying to figure out how to validate a specific scenario with jQuery validate. The user must select at least one user from a group of users, but each user in the list has a data attribute representing a score, let's say 0-100; and let's say they must select at least 1 user with a score over 70. For example...

<input type="checkbox" value="1" name="user_ids[]" id="user_ids_1" data-score="50">
<input type="checkbox" value="2" name="user_ids[]" id="user_ids_2" data-score="80">
etc...
$("form#coolForm").validate({
  rules: {
    'user_ids[]': {
      required: true,
      minLength: 1,
    }
  }
});

This will require the selection of at least one user, but is there a way to require the selection of one user where elem.data('score') >= 70 ?

1

There are 1 best solutions below

3
Hex On

I think I've got the answer

you need to add a method to the validator and get the score you want to compare, params being the number you want to compare to and return true or false (in this example if the HTML Element data-score is equal or higher than 50 it'll pass.

$.validator.addMethod("checkScore", function(value, element, params) {
        const score = $(element).data("score");
        console.log(params);
    console.log(score);
    return score >= params;
}, "This is your custom validation error message");

you can check the example here:

$.validator.addMethod("checkScore", function(value, element, params) {
        const score = $(element).data("score");
        console.log(params);
    console.log(score);
    return score >= params;
}, "This is your custom validation error message");

$(document).ready(function() {
    $('#myform').validate({
        rules: {
            "user_ids][]": {
                checkScore: 50
            },
        },
        errorPlacement: function(error, element) {
            error.insertBefore(element);
        }
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.3/jquery.validate.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.3/additional-methods.js"></script>
<form id="myform">
  <input type="checkbox" value="1" name="user_ids][]" id="user_ids_1" data-score="40">
<br/>
<input type="text" name="textfield">
<br/>
<input type="submit">
</form>