public class Others : IValidatableObject { public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { if (Name != null && Name.Length > 5) { yield return new ValidationResult("Last name has too many words", new string[] { "Name" }); } } public string Name { get; set; } }
This has a few notable differences from the attribute version.
‰ The method the MVC run time calls to perform validation is named Validate instead of
IsValid, but more important, the return type and parameters are different.
‰ The return type for Validate is an IEnumerable<ValidationResult> instead of a single
ValidationResult, because the logic inside is ostensibly validating the entire model and
might need to return more than a single validation error.
‰ There is no value parameter passed to Validate because you are inside an instance method
of the model and can refer to the property values directly.