{ Dev Farm }

Web & Windows Development

ASP.NET MVC CheckBox Validations (server and client side)

| 2 commenti

A very annoing lack in Asp.Net MVC is the checkbox validation.
I need to validate Privacy acceptation in many websites. The best way is to validate both server side and client side, in this way you can make your websites it more usable.

First: add a new validation attribute MustBeTrueAttribute. you can use it besides the other attributes in your Models

    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
    public class MustBeTrueAttribute : ValidationAttribute, IClientValidatable
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
            if ((bool)value)
                return ValidationResult.Success;
            return new ValidationResult(String.Format(ErrorMessageString, validationContext.DisplayName));

        public IEnumerable GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
            var rule = new ModelClientValidationRule
                ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
                ValidationType = "checkrequired"

            yield return rule;

Second: Extend jQuery validation to get client side check

    if (jQuery.validator) {
        // Checkbox Validation
        jQuery.validator.addMethod("checkrequired", function (value, element, params) {
            var checked = false;
            checked = $(element).is(':checked');
            return checked;
        }, '');
        if (jQuery.validator.unobtrusive) {

With these two pieces you can now easily validate your checkbox with a simple attribute.
This is a sample how it’s used:

    public class FormContact

        [Display(Name = "Name")]
        public string Name { get; set; }

        [Display(Name = "Email")]
        public string Email { get; set; }

        [Display(Name = "Privacy")]
        [MustBeTrueAttribute(ErrorMessage = "Please Accept Privacy Policy")]
        public bool Privacy { get; set; }


2 commenti

Lascia un commento

I campi obbligatori sono contrassegnati con *.