c# - ASP.NET MVC: Custom Validation by DataAnnotation -


i have model 4 properties of type string. know can validate length of single property using stringlength annotation. want validate length of 4 properties combined.

what mvc way data annotation?

i'm asking because i'm new mvc , want correct way before making own solution.

you write custom validation attribute:

public class combinedminlengthattribute: validationattribute {     public combinedminlengthattribute(int minlength, params string[] propertynames)     {         this.propertynames = propertynames;         this.minlength = minlength;     }      public string[] propertynames { get; private set; }     public int minlength { get; private set; }      protected override validationresult isvalid(object value, validationcontext validationcontext)     {         var properties = this.propertynames.select(validationcontext.objecttype.getproperty);         var values = properties.select(p => p.getvalue(validationcontext.objectinstance, null)).oftype<string>();         var totallength = values.sum(x => x.length) + convert.tostring(value).length;         if (totallength < this.minlength)         {             return new validationresult(this.formaterrormessage(validationcontext.displayname));         }         return null;     } } 

and might have view model , decorate 1 of properties it:

public class myviewmodel {     [combinedminlength(20, "bar", "baz", errormessage = "the combined minimum length of foo, bar , baz properties should longer 20")]     public string foo { get; set; }     public string bar { get; set; }     public string baz { get; set; } } 

Comments

Popular posts from this blog

node.js - Bad Request - node js ajax post -

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -