Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Validate checkbox checked required?

I'm using jQuery Validation plugin to validate a form.

The problem is that I can't find a way to validate if a single checkbox in my form is checked

HTML markup:

<label for="terms">terms : </label>
<input type="checkbox" name="terms" id="terms">

jQuery code:

rules: {
    terms: "required"
},
messages:{
    terms: "check the checbox"
}

Any help would be appreciated.

like image 438
aviad m Avatar asked Jan 18 '14 12:01

aviad m


4 Answers

Maybe your checkbox has css style

display: none

Replace it with

visibility: hidden;
width: 0;

It helped to me.

like image 122
webmustang Avatar answered Oct 29 '22 02:10

webmustang


Example of Checkbox Jquery Validation

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>

<form id="demo">
<label for="terms">terms : </label>
<input type="checkbox" name="terms[]" value="your value" id="terms">
</form>
  • give Checkbox name with square brackets.
  • Provide Value to Checkbox compulsory.

Jquery Code

$(document).ready(function() {
    $("#demo").validate({
         rules: {
               'terms[]': { required: true },
         },
         messages:{
               'terms[]': "check the checbox"
         }
     });
});
like image 42
yash dharia Avatar answered Oct 29 '22 04:10

yash dharia


HTML markup:

<label for="terms">terms : </label>
<input type="checkbox" name="terms" value="1" id="terms">

jQuery code:

rules: {
    terms: {
       required : true
    }

},
messages:{
    terms: {
        required : "check the checbox"
    }
}

jsfiddle: http://jsfiddle.net/mZ6zJ/

like image 5
ygaradon Avatar answered Oct 29 '22 03:10

ygaradon


You need to give a value to the checkbox.

<input type="checkbox" name="terms" id="terms" value="accepted">
like image 4
Barmar Avatar answered Oct 29 '22 04:10

Barmar