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?

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.