c# - Custom ValidationAttribute error not showing up in ValidationSummary (MVC 4) -


i have simple field want ensure greater number. things note:

  1. i can't install additional nuget packages.
  2. i want server-side validation.
  3. 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:

  1. enter -5 in hours text box , click submit.
  2. greaterthan's isvalid function called.
  3. the return new validationresult(formaterrormessage(validationcontext.displayname)); line hit (confirmed tracing through debugger).
  4. 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

Popular posts from this blog

c++ - QTextObjectInterface with Qml TextEdit (QQuickTextEdit) -

javascript - angular ng-required radio button not toggling required off in firefox 33, OK in chrome -

xcode - Swift Playground - Files are not readable -