c# - Custom ValidationAttribute error not showing up in ValidationSummary (MVC 4) -
i have simple field want ensure greater number. things note:
- i can't install additional nuget packages.
- i want server-side validation.
- i want use following custom validation technique rather opting pre-existing solution, because validation needs far more complex , application-specific.
here's what's happening:
- enter -5 in hours text box , click submit.
- greaterthan's isvalid function called.
- the
return new validationresult(formaterrormessage(validationcontext.displayname));
line hit (confirmed tracing through debugger). - the form posts successfully, , no errors appear in validationsummary area in view.
i expect "must greater than" error appear after calling validationsummary in view, given greaterthan class determined -5 not greater zero. idea why not case?
here's custom validation class:
public class myviewmodel { [required] [greaterthan(0)] [displayname("hours")] public string hours { get; set; } } public class greaterthan : validationattribute { private readonly float _lowerbound; public greaterthan(int lowerbound) : base("{0} must greater " + lowerbound + ".") { _lowerbound = lowerbound; } protected override validationresult isvalid(object value, validationcontext validationcontext) { if (value != null) { float result; if (float.tryparse(value.tostring(), out result) && result > _lowerbound) { return validationresult.success; } } return new validationresult(formaterrormessage(validationcontext.displayname)); } }
the view:
@using (html.beginform("myaction", "mycontroller", formmethod.post)) { @html.validationsummary() <fieldset> @html.labelfor(m => m.hours) @html.editorfor(m => m.hours) <button type="submit">submit</button> </fieldset> }
and action:
public actionresult myaction(myviewmodel model) { try { // [...] irrelevant stuff return redirecttoaction("index", "mycontroller"); } catch (exception exception) { // [...] handle exception return redirecttoaction("index", "mycontroller"); } }
why of type string? have saved lot of work if have used decimal or int. there inbuilt range validation.
the code range validation
[range(typeof(decimal), "0", "99999", errormessage = "{0} must between {1} {2}")] [required] [displayname("hours")] public decimal hours { get; set; }
Comments
Post a Comment