sf.
sf.

Reputation: 25518

Asp.Net MVC3 Model Validation string is null or if not, has min length of x

Just curious, is it possible to have Model Validation do the following:

NewPassword can be null OR If NewPassword is not null, then have a min length of 7

Upvotes: 1

Views: 1314

Answers (1)

Justin Niessner
Justin Niessner

Reputation: 245479

Using the out of the box functionality, I don't believe this is possible.

However, it is certainly possible by creating your own custom ValidationAttribute:

public class MinLengthOrNullAttribute : ValidationAttribute
{
    public int MinLength { get; set; }

    public MinLengthOrNullAttribute(int minLength)
    {
        MinLength = minLength;
    }

    public override Boolean IsValid(Object value)
    {
        return value == null || (value as string).Length > minLength;
    }
}

Upvotes: 6

Related Questions