DarLom
DarLom

Reputation: 1110

Why is StringLength not validated when using ValidationContext outside of MVC?

I have a data entry page in my MVC application and have defined data annotations for validating the input. This works as expected.

I also have a file upload that needs to validate the incoming data with the same rules, so instead of writing the rules again, I decided to map each row into an instance of the model class so I could use the same validation rules outside of a controller (described in other SO answers.)

The [Required] attribute works, but the others I use, StringLength and Range, do not. Here's a sample that I tested in LinqPad with the same result:

void Main()
{
    var model = new Model { Name = "Test String" };
    var validationResults = new List<ValidationResult>();
    var validationContext = new ValidationContext(model, null, null);
    Validator.TryValidateObject(model, validationContext, validationResults);
    validationResults.Select(w => w.ErrorMessage).Dump();
}

// Define other methods and classes here
public class Model
{
    [Required, StringLength(8, MinimumLength = 1, ErrorMessage = "String length is outside of range.")]
    public string Name { get; set; }
}

I would expect the StringLength to cause a validation error since it is greater than the max length of 8, but it does not. What am I missing?

Upvotes: 0

Views: 822

Answers (1)

Lanorkin
Lanorkin

Reputation: 7504

You need to add one more parameter:

Validator.TryValidateObject(model, validationContext, validationResults, true);

Without that, it validates only for "Required".

MSDN link

validateAllProperties Boolean

true to validate all properties; if false, only required attributes are validated

Upvotes: 2

Related Questions