I have a Razor view which renders some drops downs using HTML helpers and others using jQuery DataTable,
<div class="form-group">
@Html.LabelFor(model => model.CarTyres, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-2">
@Html.ListBoxFor(model => model.SelectedCarTyres, Model.CarTyres, htmlAttributes: new { @class = "selectpicker form-control", @multiple = "", @data_actions_box = "true" })
@Html.ValidationMessageFor(model => model.SelectedCarTyres, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Drivers, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-2">
@Html.ListBoxFor(model => model.SelectedDrivers, Model.Drivers, htmlAttributes: new { @class = "selectpicker form-control", @multiple = "", @data_actions_box = "true" })
@Html.ValidationMessageFor(model => model.SelectedDrivers, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.CarJacks, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-5">
<table id="filtersTable">
<thead>
<tr>
<th>Select</th>
<th>Name</th>
</tr>
</thead>
</table>
</div>
@Html.ValidationMessageFor(model => model.CarJacksCheckBox, "", new { @class = "text-danger" })
</div>
In my model , I am setting the required to true so that when I check Model.IsValid()
will return false if any of those items are not set, and that works fine.
public class ReportViewModel
{
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
[Required]
public ICollection<int> SelectedCarTyres { get; set; }
public IEnumerable<SelectListItem> CarTyres { get; set; }
[Required]
public ICollection<int> SelectedDrivers { get; set; }
public IEnumerable<SelectListItem> Drivers { get; set; }
public IEnumerable<CarJackViewModel> CarJacks { get; set; }
[Required]
public string SelectedSampleTime { get; set; }
public IEnumerable<SelectListItem> SampleTimes { get; set; }
[Required]
public IEnumerable<int> CarJacksCheckBox { get; set; }
}
To make javascrip data tables required , I copied the vallidation attributes on checkbox(es) like following:
$('#filtersTable').DataTable(
{
"iDisplayLength": 25,
"ajax": {
"url": "/CarJacks/Loaddata",
"type": "GET",
"datatype": "json"
},
"columns": [
{
"data": "IsSelected",
"render": function (data, type, row) {
if (type === 'display') {
return '<input type="checkbox" name="CarJacksCheckBox" class="editor-active" data-val="true" data-val-required="The CarJacks field is required.">';
}
return data;
}
],
"rowCallback": function (row, data) {
//Removed for Brevity
}
}
);
But still , I am not getting any client side validation when none of the CarJackCheckBox are selected.
Though (ModelState.IsValid)
is returning false, $(form).valid()
returning true and hence no errors on client side.
Which piece am I missing ?
You cannot use MVC's client side validation because validation rules are applied to form controls, and you do not (and cannot) create a form control for your IEnumerable<int> CarJacksCheckBox
property. You need to write your own script to validate that at least one checkbox is required.
Remove the data-val-*
attributes from the checkbox (since they are pointless) and add an additional class name, say carjacks
to use in the script as a jQuery selector.
Then include the following scripts (note these mimic 'lazy' validation - it first validates on submit, and thereafter on clicking a checkbox)
var validateOnClick = false; // for lazy validation
var requiredCarJacks = 1;
var carJacks= $('.carjacks');
var errorMessage = 'Select at least 1 car jack';
var errorElement = $('span[data-valmsg-for="CarJacksCheckBox"]');
function validateCarJacks() {
var selectedCarJacks = carJacks.filter(':checked').length;
var isValid = selectedCarJacks > requiredCarJacks ;
if (!isValid) {
errorElement.addClass('field-validation-error').removeClass('field-validation-valid').text(errorMessage);
} else {
errorElement.addClass('field-validation-valid').removeClass('field-validation-error').text('');
}
return (isValid);
}
$('form').submit(function () {
if (!validateCarJacks()) {
validateOnClick = true; // signal that we should now validate the .click() event
return false; // prevent submit
}
});
carJacks.click(function() {
if (validateOnClick) {
validateCarJacks();
}
})