The StringLength
attribute specifies the minimum and maximum length of characters that are allowed in a data field. This attribute can be applied on properties, public fields and parameters. The error message must be specified on the ErrorMessage
property on the attribute. The properties MinimumLength
and MaximumLength
specifies the minimum and maximum respectively.
First add the namespace:
using System.ComponentModel.DataAnnotations;
And apply the attribute on a property.
public class User
{
// set the maximum
[StringLength(20, ErrorMessage = "The username cannot exceed 20 characters. ")]
public string Username { get; set; }
[StringLength(MinimumLength = 3, MaximumLength = 16, ErrorMessage = "The password must have between 3 and 16 characters.")]
public string Password { get; set; }
}
It is also possible to use resources in the error message for globalized applications. In this case, the ErrorMessageResourceName
must be specified with the resource key of the resource class (resx
file) that must be setted on the ErrorMessageResourceType
:
public class User
{
[StringLength(20, ErrorMessageResourceName = "StringLength",
ErrorMessageResourceType = typeof(ResoucesKeys))]
public string Username { get; set; }
[StringLength(MinimumLength = 3,
MaximumLength = 16,
ErrorMessageResourceName = "StringLength",
ErrorMessageResourceType = typeof(ResoucesKeys))]
public string Password { get; set; }
}