i have many checkboxes and i want user has to select one. if none selected then validation message will be selected. here is my code but validation message is not showing.
checkbox html
<div class="col-md-offset-2 col-md-10">
<b>Hobbies</b><br>
<input type="checkbox" value="true" name="Hobbies[0].IsSelected" id="Hobbies_0__IsSelected" data-val-required="The IsSelected field is required." data-val="true" class="hobbycls input-validation-error"><input type="hidden" value="false" name="Hobbies[0].IsSelected">
<label for="Hobbies_0__IsSelected">Reading</label>
<input type="hidden" value="Reading" name="Hobbies[0].Name" id="Hobbies_0__Name"><input type="checkbox" value="true" name="Hobbies[1].IsSelected" id="Hobbies_1__IsSelected" data-val-required="The IsSelected field is required." data-val="true" class="hobbycls input-validation-error"><input type="hidden" value="false" name="Hobbies[1].IsSelected">
<label for="Hobbies_1__IsSelected">Sports</label>
<input type="hidden" value="Sports" name="Hobbies[1].Name" id="Hobbies_1__Name"><input type="checkbox" value="true" name="Hobbies[2].IsSelected" id="Hobbies_2__IsSelected" data-val-required="The IsSelected field is required." data-val="true" class="hobbycls input-validation-error"><input type="hidden" value="false" name="Hobbies[2].IsSelected">
<label for="Hobbies_2__IsSelected">Movies</label>
<input type="hidden" value="Movies" name="Hobbies[2].Name" id="Hobbies_2__Name"> <span data-valmsg-replace="true" data-valmsg-for="Hobbies" class="field-validation-valid"></span>
jquery unobtrusive validation code
$(function () {
$.validator.addMethod("CheckOneCategory", function (value, element) {
//var tag = $(".col-md-offset-2 col-md-10").find(":checkbox");
//alert(tag.filter(':checked').length);
//return tag.filter(':checked').length;
if ($(".hobbycls:checkbox:checked").length > 0) {
return true;
} else {
alert('hello');
return false;
}
}, "Select at least one hobby");
$.validator.addClassRules("hobbycls", { CheckOneCategory: true });
});
Aucun commentaire:
Enregistrer un commentaire