I have the following property in my Model :
[StringLength(100, ErrorMessage = "Must be less than 100 Chars", MinimumLength = 3)]
public List<KeyValuePair<int, string>> Authors { get; set; }
How can I Validate each string into the above list with DataAnnotation Validation attribute in MVC3 ?
Is it possible at all ?
Custom validation to the rescue! You need to do the following:
IValidatableObjectinterfaceIEnumerable<ValidationResult> Validate(ValidationContext validationContext)Here’s the code
That way you can do a call to
if(Model.IsValid)in your controller action, and return any errors that are reported. If yourKeyValuePairentries are referring to a specific entity you can even do something like:You’d need to tailor it to fit the ID of the attribute on your page. This way, the error message could be specific to an input on your page.
I override
IValidatableObjectin many places as there’s many cases where I do validation that’s dependent on the state of my object. Your case is a bit different, but it’s certainly do-able as can be seen from the above example. (All that’s off the top of my head, however, so may not be perfect!)