How to create an ASP.NET MVC3 validator for the minimum and maximum number of flags?

I would like to have a reusable validator that I can use in the group of checkbox fields that will allow me to specify the minimum quantity that I need to select and the maximum quantity that I can choose. I don’t know exactly how to create server-side validation and client-side validation in order to connect to the jQuery validation framework using unobtrusive javascript.

This question seems like a good start for the client adapter, but how do you bundle it all together to test it on the server?

+4
source share
2 answers

Here you can start at least server-side verification. Here is a very good article that illustrates several 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) 
+5
source

Brad Wilson had an excellent presentation about mvcConf about validation in mvc.

+1
source

Source: https://habr.com/ru/post/1345728/


All Articles