Reputation: 660
I am currently using MVC Data Annotations to perform validation on my model.
[MinLength(4, ErrorMessage = "The {0} must be at least {2} characters long")]
[MaxLength(16, ErrorMessage = "The {0} must be {2} characters long or less")]
[DataType(DataType.Password)]
[Display(Name = "New Password")]
public string Password { get; set; }
However, I'm stuck dealing with a field that is not required, but needs to have a MinLength when there is something in the input field. Simply removing
[Required]
does not help. Is there any way to do this without creating yet another custom validation attribute?
Upvotes: 2
Views: 3320
Reputation: 236188
Seems like your property has empty or white space string value, because MinLength
attribute considers null
as a valid value:
public override bool IsValid(object value)
{
this.EnsureLegalLengths();
int length = 0;
if (value == null)
{
return true; // <-- null is valid!
}
string str = value as string;
if (str != null)
{
length = str.Length;
}
else
{
length = ((Array) value).Length;
}
return (length >= this.Length);
}
Upvotes: 3
Reputation: 18237
The annotation that you're looking for it's
[StringLength(100, ErrorMessage = "The {0} have to be {2} characters.", MinimumLength = 8)]
public string Password { get; set; }
Upvotes: 2