c# - Using parameter for StringLength attribute -
the code generated asp.net mvc 3 membership, escpecially property newpassword
of class changepasswordmodel
looks like:
[required] [stringlength(100, minimumlength=6)] [datatype(datatype.password)] [display("name = currentpassword")] public string newpassword { get; set; }
in order to fill information external parameters using recourcetype:
(in case changing oldpassword
, fill attribute display
additional data resource
[required] [datatype(datatype.password)] [display(resourcetype = typeof(account), name = "changepasswordcurrent")] public string oldpassword { get; set; }
back newpassword
. how can substitute minimumlenght
membership.minrequiredpasswordlength
? : attempt:
[required] [stringlength(100, minimumlength=membership.minrequiredpasswordlength)] [datatype(datatype.password)] [display(resourcetype=typeof(account), name= "changepasswordnew")] public string newpassword { get; set; }
this produces error:
an attribute argument must constant expression, typeof expression or array creation expression of attribute parameter type (http://msdn.microsoft.com/de-de/library/09ze6t76%28v=vs.90%29.aspx)
validation attributes must compiled constants (like error message states). create own validationattribute handles minimum length you.
[attributeusage(attributetargets.field | attributetargets.property, allowmultiple = false, inherited = true)] public sealed class validatepasswordlengthattribute : validationattribute { private const string defaulterrormessage = "'{0}' must @ least {1} characters long."; private readonly int _mincharacters = membership.provider.minrequiredpasswordlength; public validatepasswordlengthattribute() : base(defaulterrormessage) { } public override string formaterrormessage(string name) { return string.format(cultureinfo.currentuiculture, errormessagestring, name, _mincharacters); } public override bool isvalid(object value) { var valueasstring = value.tostring(); return (valueasstring != null) && (valueasstring.length >= _mincharacters); } }
then view model (you more fancy , add max length part of dataannotations in validatepasswordlength attribute remove line)
[required] [stringlength(100)] [datatype(datatype.password)] [display(resourcetype=typeof(account), name= "changepasswordnew")] [validatepasswordlength] public string newpassword { get; set; }
Comments
Post a Comment