Dataannotations provides requiredattriations for null, empty, and stringlengthattribute for String Length verification. It is strange that a stringlengthrangeattribute verification is not provided. For example, when verifying input, the password may be in the range of 6-20. At this time, we can expand a validationattribute, which is simple: [Attributeusage (attributetargets. Field | Attributetargets. Property
, Allowmultiple = False , Inherited = True )]
Public Class Stringlengthrangeattribute: validationattribute
{
Private Const String _ Defaulterrormessage = " The length of '{0}' must be between {1}-{2} characters. " ;
Public Stringlengthrangeattribute ( Int Minlength, Int Maxlength)
: Base (_ Defaulterrormessage)
{
If (Minlength < 0 )
Throw New Argumentoutofrangeexception ( " Minlength " , Minlength
, " The minimum length of a string cannot be less than 0. " );
If (Maxlength < 0 )
Throw New Argumentoutofrangeexception ( " Maxlength " , Maxlength
, " The maximum length of a string cannot be less than 0. " );
If (Maxlength <= Minlength)
Throw New Argumentoutofrangeexception ( " Maxlength " , Maxlength
, " The maximum length of a string must be greater than the minimum length. " );
Minlength = Minlength;
Maxlength = Maxlength;
}
Public Override Bool Isvalid ( Object Value)
{
String Valueasstring = Value As String ;
If (String. isnullorempty (valueasstring )) Return True ;
Return Valueasstring. Length > = Minlength
&& Valueasstring. Length <= Maxlength;
}
Public Override String Formaterrormessage ( String Name)
{
Return String. Format (cultureinfo. currentuiculture, errormessagestring,
Name, minlength, maxlength );
}
Public Int Maxlength
{
Get ;
Private Set ;
}
Public IntMinlength
{
Get;
Private Set;
}
}
Example:
Public Class Userinputedit
{
[Stringlengthrange ( 6 , 20 , Errormessage = " The logon password must be between 6 and 20 characters. " )]
[Displayname ( " Logon Password " )]
Public String Password { Get ; Private Set ;}
}< br>
Note :. net 4, system. componentmodel. the stringlengthattribute in the dataannotations namespace adds the minimumlength attribute to set the minimum String Length.