If someone is interested in adding jquery validation (so that the checkbox is checked both in the browser and on the server), you should change the BooleanMustBeTrueAttribute class as follows:
public class BooleanMustBeTrueAttribute : ValidationAttribute, IClientValidatable { public override bool IsValid(object propertyValue) { return propertyValue != null && propertyValue is bool && (bool)propertyValue; } public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { yield return new ModelClientValidationRule { ErrorMessage = this.ErrorMessage, ValidationType = "mustbetrue" }; } }
Basically, the class now also implements IClientValidatable and returns the corresponding js error message and the jquery validation attribute, which will be added to the HTML field ("mustbetrue").
Now, to check if jquery is working properly, add the following js to the page:
jQuery.validator.addMethod('mustBeTrue', function (value) { return value;
Note. I based the previous code on the one used in this answer -> Perform client side validation for a custom attribute
And that basically it :)
Remember that for the previous js to work, you had to include the following js files on the page:
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
PS When you have a job, I would recommend adding the code in the js file to the Scripts folder and creating a package with all js files.
source share