Critical Developers

Programmers Knowledge Base

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; }

Comments (1) -

  • Sumesh

    31-10-2016 18:03:49 |

    Thanks for the solution this did work for me Smile

Comments are closed