c# - Missing form validation in MVC application -
i have form containing check boxes, , know can make each 1 required enforce validation errors. looking for, error if none of boxes has been checked. how go achieving this?
i looking error message like: "you must select @ least 1 property."
i should clarify none of fields required individually, there should @ least 1 chosen option.
edit clarification:
my view looks this:
@using (html.beginform("method", "controller", formmethod.post, new {id = "id"})) { @html.antiforgerytoken() @html.validationsummary(true, "", new { @class = "text-danger" }) <div class="form-group"> @html.labelfor(model => model.property1, htmlattributes: new { @class = "control-label col-md-4" }) <div class="col-md-8"> @html.checkboxfor(model => model.property1) </div> </div> <div class="form-group"> @html.labelfor(model => model.property2, htmlattributes: new { @class = "control-label col-md-4" }) <div class="col-md-8"> @html.checkboxfor(model => model.property2) </div> </div> <div class="form-group"> @html.labelfor(model => model.property3, htmlattributes: new { @class = "control-label col-md-4" }) <div class="col-md-8"> @html.checkboxfor(model => model.property3) </div> </div> }
my view model looks this:
public class formvm { [display(name = "one")] public bool property1 {get;set;} [display(name = "two")] public bool property2 {get;set;} [display(name = "three")] public bool property3 {get;set;} }
you can implement ivalidatableobject
interface on viewmodel:
public class formvm : ivalidatableobject { [display(name = "one")] public bool property1 {get;set;} [display(name = "two")] public bool property2 {get;set;} [display(name = "three")] public bool property3 {get;set;} public ienumerable<validationresult> validate(validationcontext validationcontext) { var results = new list<validationresult>(); if (!(property1 || property2 || property3)) { results.add(new validationresult("you must select @ least 1 property.")); } return results; } }
the benefit of using this fired automatically if call modelstate.isvalid
in controller, , error message added modelstate
errors.
Comments
Post a Comment