MaxLength is used for the Entity Framework to decide how large to make a string value field when it creates the database.
From MSDN:
Specifies the maximum length of array or string data allowed in a property.
StringLength is a data annotation that will be used for validation of user input.
From MSDN:
Specifies the minimum and maximum length of characters that are allowed in a data field.
Use [String Length]
[RegularExpression(@"^.{3,}$", ErrorMessage = "Minimum 3 characters required")]
[Required(ErrorMessage = "Required")]
[StringLength(30, MinimumLength = 3, ErrorMessage = "Maximum 30 characters")]
30 is the Max Length
Minimum length = 3
public class MyStringLengthAttribute : StringLengthAttribute
{
public MyStringLengthAttribute(int maximumLength)
: base(maximumLength)
{
}
public override bool IsValid(object value)
{
string val = Convert.ToString(value);
if (val.Length < base.MinimumLength)
base.ErrorMessage = "Minimum length should be 3";
if (val.Length > base.MaximumLength)
base.ErrorMessage = "Maximum length should be 6";
return base.IsValid(value);
}
}
public class MyViewModel
{
[MyStringLength(6, MinimumLength = 3)]
public String MyProperty { get; set; }
}