4

I'd like to have a reusable validator that I can use on a group of checkbox fields that will let me specify a minimum number to be selected and maximum number that can be selected. I'm not sure exactly how to create both the server side check and the client side validation to hook into the jQuery validate framework using unobtrusive javascript.

This question seems to be a good start on the client side adapter, but how do you tie it all together to validate it on the server?

Community
  • 1
  • 1
Austin
  • 4,638
  • 7
  • 41
  • 60

2 Answers2

5

Here's how you could start at least for server side validation. Here's a very nice article that illustrates multiple concepts.

Validation attribute:

public class CheckBoxesValidationAttribute : ValidationAttribute
{
    public CheckBoxesValidationAttribute (int min, int max)
    {
        Min = min;
        Max = max;
    }

    public int Min { get; private set; }
    public int Max { get; private set; }

    public override bool IsValid(object value)
    {
        var values = value as IEnumerable<bool>;
        if (values != null)
        {
            var nbChecked = values.Where(x => x == true).Count();
            return Min <= nbChecked && nbChecked <= Max;
        }
        return base.IsValid(value);
    }
}

Model:

public class MyViewModel
{
    [CheckBoxesValidation(1, 2, ErrorMessage = "Please select at least one and at most 2 checkboxes")]
    public IEnumerable<bool> Values { get; set; }
}

Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel
        {
            Values = new[] { true, false, true, false }
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        return View(model);
    }
}

View (~/Views/Home/Index.cshtml):

@Html.ValidationSummary()
@using (Html.BeginForm()) 
{
    @Html.EditorFor(x => x.Values)
    <input type="submit" value="OK" />
}

Editor template (~/Views/Home/EditorTemplates/bool.cshtml):

@model bool
@Html.CheckBoxFor(x => x)
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
1

Brad Wilson had great presentation on mvcConf about validation in mvc.

archil
  • 39,013
  • 7
  • 65
  • 82