c# - MVC 5 not validating StringLength attribute properly -
i'm trying validate sortcode field in personpaymentdetails model view failing validate stringlength(6). if submit form value of length 1 incorrectly validates successfully.
am doing fundamentally wrong here?
/* [controller] */ public class personcontroller : controller { [httpget] [route("person/paymentdetails/create/{personid?}")] public actionresult paymentdetailscreate(int? personid) { if (personid == null) { return new httpstatuscoderesult(httpstatuscode.badrequest); } person person = db.people.find(personid); if (person == null) { return httpnotfound(); } personpaymentdetailsviewmodel personpaymentdetailsvm = new personpaymentdetailsviewmodel(); personpaymentdetailsvm.setperson(person); return view(personpaymentdetailsvm); } [httppost] [route("person/paymentdetails/create")] public actionresult paymentdetailscreate(personpaymentdetailsviewmodel personpaymentdetailsvm) { if (modelstate.isvalid) { /* should not entering here sortcode = 123, not 6 characters in length */ return content("no errors: |" + personpaymentdetailsvm.singlepaymentdetails.sortcode + "|"); } } } /* [view] */ @model x.viewmodels.personpaymentdetailsviewmodel @html.validationsummary() @using (html.beginform("paymentdetailscreate", "person", formmethod.post, new { @class = " form-horizontal" })) { @html.hiddenfor(m => m.person.id, "default") <div class="form-group"> <label for="banksortcode" class="col-md-3 control-label">sort code</label> <div class="col-md-9"> @html.editorfor(m => m.singlepaymentdetails.sortcode, new { htmlattributes = new { @class = "form-control" } }) </div> </div> <div class="form-group"> <label for="save" class="col-md-3 control-label"> </label> <div class="col-md-9"> <button type="submit" class="btn btn-primary">save</button> </div> </div> } /* [model] */ public partial class personpaymentdetails { public int id { get; set; } [required, stringlength(6)] public string sortcode { get; set; } } /* [viewmodel] */ public class personpaymentdetailsviewmodel { public person person { get; set; } public personpaymentdetails singlepaymentdetails { get; set; } public void setperson(person person) { this.person = person; this.singlepaymentdetails = new personpaymentdetails(); } }
you want
[required, stringlength(6, minimumlength = 6)]
constructor of stringlength
takes in maximum length only, have it checks string not longer 6 characters, , therefore string of length 1 passes validation successfully.
Comments
Post a Comment