How can I validate in bootstrap that at least one checkbox is marked and pass this information to php?
Solution 1
You can name the checkbox array whatever makes sense (I used number[]
as a generic example), then add your rules and/or messages as usual.
You can use custom errorPlacement rules to add messages where appropriate. There's a target div for the checkbox array that's places in your HTML (<div id="checkboxGroup"></div>
).
See docs: jQuery Validate
$('#myform').validate({
rules: {
datetimepicker: {
required: true,
date: true
},
commercialText: {
required: true,
minlength: 5
},
terms: {
required: true,
minlength: 1
},
'number[]': {
required: true,
minlength: 1,
maxlength: 2
}
},
messages: {
datetimepicker: {
required: "Please enter a date."
},
commercialText: {
required: "Please enter your message."
},
terms: {
required: "Please agree to terms."
},
'audit[]': {
required: "Please check at least 1 option.",
minlength: "Please check at least {0} option."
}
},
submitHandler: function(form) {
var text = $("#customtext").val();
var date = $("#datetimepicker").val();
var stand = 2;
$.ajax({
url: 'savedatanow.php',
type: "POST",
data: {
text: text,
date: date,
stand: stand
},
dataType: 'text',
success: function(response) {
alert(response);
}
});
//alert('outside ajax');
},
highlight: function(element) {
$(element).closest('.form-group').removeClass('has-success').addClass('has-error');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error').addClass('has-success');
},
errorClass: 'help-block',
errorPlacement: function(error, element) {
if (element.parent('.form-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element.parent());
}
if (element.attr('name') == 'number[]') {
error.insertAfter('#checkboxGroup');
} else {
error.appendTo(element.parent().next());
}
}
});
#myform .has-error .help-block {
display: block;
border: none;
color: #737373;
padding-top: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.14.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.14.0/additional-methods.min.js"></script>
<div class="container">
<form role="form" id="myform">
<div class="form-group">
<label>what is your number?</label>
<div class="col-lg-12">
<div class="col-lg-6">
<div class="checkbox">
<label>
<input name="number[]" type="checkbox" value="">one</label>
</div>
<div class="checkbox">
<label>
<input name="number[]" type="checkbox" value="">two</label>
</div>
<div class="checkbox">
<label>
<input name="number[]" type="checkbox" value="">three</label>
</div>
<div class="checkbox">
<label>
<input name="number[]" type="checkbox" value="">four</label>
</div>
</div>
<div class="col-lg-6">
<div class="checkbox">
<label>
<input name="number[]" type="checkbox" value="">five</label>
</div>
<div class="checkbox">
<label>
<input name="number[]" type="checkbox" value="">six</label>
</div>
<div class="checkbox">
<label>
<input name="number[]" type="checkbox" value="">seven</label>
</div>
<div class="checkbox">
<label>
<input name="number[]" type="checkbox" value="">eight</label>
</div>
</div>
</div>
<div id="checkboxGroup"></div>
</div>
<div class="form-group">
<label for="datetimepicker">When do you want to go?</label>
<input type="text" class="form-control" id="datetimepicker" name="datetimepicker" />
</div>
<div class="form-group">
<label>How long will it last?</label>
<select class="form-control">
<option>5 seconds</option>
<option>10 seconds</option>
<option>15 seconds</option>
<option>20 seconds</option>
<option>30 seconds</option>
</select>
</div>
<div class="form-group">
<label for="commercialText">Write a text that:</label>
<textarea class="form-control" rows="3" id="commercialText" name="commercialText" placeholder="hello"></textarea>
</div>
<div class="form-group">
<label class="checkbox-inline">
<input type="checkbox" id="terms" name="terms">I accept the terms</label>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
Solution 2
Create custom validator for group of elements.
$.validator.addMethod( "at_least_one", function() {
return $( "input[name='number[]']:checked" ).length;
}, 'Select at least one number' );
Add rule.
rules: {
"number[]": "at_least_one",
.....
Add name and value attributes to checkboxes, here is an example of how to creates an array of the selected values with square braces to the checkbox names. That way $_POST['number']
will be an array of checked values.
<input type="checkbox" value="two" name="number[]">
For dates you can use jQuery Datepicker or THIS SO question, basically create another custom validation method.
Now, there is still some issues with error messages and bootstrap, I hope that someone else will help you with that.
randomuser1
Updated on September 21, 2020Comments
-
randomuser1 over 3 years
I'm using bootstrap and I created a form with 8 checkboxes. When user clicks "Submit" I want to verify if at least one checkbox is marked and if not - let user know with an error message below the checkbox group. Also, I would like to verify if the date that he puts is correct with my default data-form: 23/09/2015 05:45 PM
This is my java-script validation code:
$('#myform').validate({// initialize the plugin errorElement: 'div', rules: { datetimepicker: { required: true, date: true }, commercialText: { required: true, minlength: 5 }, terms: { required: true, maxlength: 2 } }, submitHandler: function (form) { var text = $("#customtext").val(); var date = $("#datetimepicker").val(); var stand = 2; $.ajax({ url: 'savedatanow.php', type: "POST", data: { text: text, date: date, stand: stand }, dataType:'text', success: function(response) { alert(response); } }); //alert('outside ajax'); }, highlight: function (element) { $(element).closest('.form-group').removeClass('success').addClass('has-error'); }, success: function (element) { element.addClass('valid') .closest('.form-group').removeClass('error').addClass('has-success'); } });
I prepared the following fiddle: http://jsfiddle.net/5WMff/1316/ but I have a problem with marking the correct error messages in red. When user doesn't check that he accepts the terms there's a weird situation happening too (the whole text is marked in red, not only the error)... Can you help me with that? Thanks!
-
Dejell over 7 yearsThanks. why is the select new number is added as a new checkbox?