.NET mvc3 validation minimumlength, but not requir

2019-07-15 13:02发布

问题:

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?

回答1:

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);
}


回答2:

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; }