2

I'm trying to implement a required validation on a group of checkboxes. Basically one of them needs to be checked and the number of checkboxes is dynamic. I'm not excactly confident in the code below, I'm starting to assume I might need to use Javascript. I think the code speaks best for itself.

HTML:

       @for (var i = 0; i < Model.Sessions.Count(); i++ )
    {
        @Html.HiddenFor(it => it.Sessions[i].Id)
        @Html.LabelFor(it => it.Sessions[i].Name, Model.Sessions[i].Name)
        @Html.CheckBoxFor(it => it.Sessions[i].Checkbox)
    }
    @Html.ValidationMessageFor(model => model.Sessions)

C# (Viewmodel):

    [NotNull]
    [GlobalisedRequired]
    public virtual List<CheckBoxModel> Sessions { get; set; }
PanJanek
  • 6,593
  • 2
  • 34
  • 41
Asgeir
  • 727
  • 3
  • 9
  • 20
  • You could create a jQuery validation script that will take a list of checkboxes and make sure one of them is checked. You would have to add some sort of server validation as well, though. – Dismissile Jun 06 '12 at 13:50

1 Answers1

1

Instead of RequiredAttribute (you will always get value from checkbox) you should use custom validator, like described here:

How would you validate a checkbox in ASP.Net MVC 2?

And then add [BooleanRequiredToBeTrue] attribute to Checkbox property inside CheckBoxModel class.

And of course you could use javascript client-side validation but validation on the server side is necessary too.

Community
  • 1
  • 1
PanJanek
  • 6,593
  • 2
  • 34
  • 41
  • That didn't work, and I think that if it did it would cause me to have to check every one of the checkboxes. I do have server side validation. I mainly want to have a unified way of doing validation, and I've mostly been able to do without javascript so far. – Asgeir Jun 06 '12 at 13:33
  • @Asgeir: I updated my answer - [Required] attribute will check if there is a value in the field, and there will be always (true of false). You need to use custom validator that will check if the value is true – PanJanek Jun 06 '12 at 13:45
  • Thanks, that does help somewhat, but the solution linked to is to a problem where there is only one checkbox that needs to be checked. I don't need all the boxes to be checked, just any one of them. Is it possible to do the IsValid override for a list ? – Asgeir Jun 06 '12 at 13:59
  • @Asgeir: If you want to validate if there is only one checkbox checked you need to write custom validation attribute and use it on Sessions property. Even better solution would be using validation framework like FluentValidation for MVC - it makes writing custom validators easier. – PanJanek Jun 06 '12 at 14:08
  • Thanks for your help, I ended up using JQuery since the senior developer here OKd it for this. I'll definitely check out FluentValidation, thanks for the tip. – Asgeir Jun 06 '12 at 16:20