I've got a class that has [Required]
decorations on some attributes, but also needs some custom validation, so it uses IValidatableObject
.
Class
public class ModelCourse : IValidatableObject
{
//some other code...
[DisplayName("Course Name")]
[Required]
[StringLength(100, MinimumLength=1)]
public String name { get; set; }
//more code...
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (courseGradeLevels == null || courseGradeLevels.Count < 1)
{
yield return new ValidationResult("You must select at least one grade level.");
}
if ((courseLength == CourseLength.Other) && string.IsNullOrEmpty(courseLengthDescription))
{
yield return new ValidationResult("Course Length Description is Required if Length is Other.");
}
}
}
Validation
//course is one of a few child objects in this class
bool dbDetailsValid = TryValidateModel(dbDetails);
ViewData["courseValid"] = !ModelState.ContainsKey("course");
foreach(KeyValuePair<string, ModelState> pair in ModelState.Where(x => x.Value.Errors.Count > 0))
{
ViewData[pair.Key + "ErrorList"] = pair.Value.Errors.ToList();
}
When I run this code, a blank string for name
doesn't result in an error in ModelState
. The custom validation logic works as expected, but I don't get why TryValidateModel
isn't picking up on the decorations... is my only option to manually check each required field?