You can specify the StringLength attribute as follows on numerous properties
[StringLength(20, ErrorMessageResourceName = "StringLengthMessage", ErrorMessageResourceType = typeof(Resource))]
public string OfficePhone { get; set; }
[StringLength(20, ErrorMessageResourceName = "StringLengthMessage", ErrorMessageResourceType = typeof(Resource))]
public string CellPhone { get; set; }
and add the string resource (named StringLengthMessage
) in your resource file
"Maximum length is {1}"
Message is defined once and has a variable place holder should you change your mind regarding the length to test against.
You can specify the following:
- {0} – Name
- {1} – Maximum Length
- {2} – Minimum Length
Update
To minimize duplication even further you can subclass StringLengthAttribute:
public class MyStringLengthAttribute : StringLengthAttribute
{
public MyStringLengthAttribute() : this(20)
{
}
public MyStringLengthAttribute(int maximumLength) : base(maximumLength)
{
base.ErrorMessageResourceName = "StringLengthMessage";
base.ErrorMessageResourceType = typeof (Resource);
}
}
Or you can override FormatErrorMessage
if you want to add additional parameters. Now the properties look as follows:
[MyStringLength]
public string OfficePhone { get; set; }
[MyStringLength]
public string CellPhone { get; set; }