Critical Developers

Programmers Knowledge Base

Validate CheckBox as Required Field in ASP.Net MVC

Validate CheckBox Must be true in Asp.Net MVC

Many times we want users to accept the terms and condition to proceed using a checkbox.
Lets learn how to validate CheckBox as required field in ASP.Net MVC. The logic is very simple.
Markups for same is written below. Add validation adapter to your custom js and write same logic in your model.
Then you can simply annotate the attribute.

Markups for CheckBox in View :-
@Html.CheckBoxFor(model => model.is_accepted)) Please accept to proceed.
@Html.ValidationMessageFor(model => model.is_accepted)

Add Custom Validator in your custom js file :-

jQuery.validator.unobtrusive.adapters.add("checkboxtrue", function (options) {
    if (options.element.tagName.toUpperCase() == "INPUT" && options.element.type.toUpperCase() == "CHECKBOX") {
        options.rules["required"] = true;
        if (options.message) {
            options.messages["required"] = options.message;
        }
    }
});

Register "MustBeTrue" Custom Validator in your Model :-

    public class MustBeTrueAttribute : ValidationAttribute, IClientValidatable
    {
        public override bool IsValid(object value)
        {
            return value is bool && (bool)value;
        }
        // Implement IClientValidatable for client side Validation
        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            return new ModelClientValidationRule[] { new ModelClientValidationRule { ValidationType = "checkboxtrue", ErrorMessage = this.ErrorMessage } };
        }
    }

Data Annotation Attribute for same is below :-


        [MustBeTrue(ErrorMessage = "This field is required.")]
        public object is_accepted { get; set; }

Check atleast one checkbox from Multiple Checkboxes in ASP.Net MVC or Validate CheckBoxList in ASP.Net MVC

So, today I will explain you how to use validation for selecting one checkbox is mandatory among multiple checkboxes.
The idea behind is,  we will have to create multiple checkbox with one hiddenfield as shown below.

Markups :-

<input type="checkbox" name="stCategory" value="1" @(Model.stCategory.Contains("1") ? "checked" : "") />
<input type="checkbox" name="stCategory" value="2" @(Model.stCategory.Contains("2") ? "checked" : "") />
<input type="checkbox" name="stCategory" value="5" @(Model.stCategory.Contains("5") ? "checked" : "") />
<input type="checkbox" name="stCategory" value="6" @(Model.stCategory.Contains("6") ? "checked" : "") />
@Html.HiddenFor(model => model.stCategory)
@Html.ValidationMessageFor(model => model.stCategory)

Add Custom Validator in your custom js file :-

jQuery.validator.unobtrusive.adapters.add("atleastonetrue", function (options) {
    if (options.element.tagName.toUpperCase() == "INPUT" && options.element.type.toUpperCase() == "HIDDEN") {
        options.rules["required"] = true;
        if (options.message) {
            options.messages["required"] = options.message;
        }
    }
});

Register Custom Validator in your Model :-

    public class AtleastOneAttribute : ValidationAttribute//, IClientValidatable
    {
        // For Server side
        public override bool IsValid(object value)
        {
            if (value != null && value != string.Empty)
            {
                return true;
            }
            return false;
        }
        // Implement IClientValidatable for client side Validation
        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            return new ModelClientValidationRule[] { new ModelClientValidationRule { ValidationType = "atleastonetrue", ErrorMessage = this.ErrorMessage } };
        }
    }

And here is your Data Annotation Attribute :-

[Required(ErrorMessage = "This field is required.")]
[AtleastOne(ErrorMessage = "Select atleast one checkbox.")]
public object stWordDescPain { get; set; }