I understand that IValidatableObject
is used to validate an object in a way that lets one compare properties against each other.
I\'d still like to have
Just to add a couple of points:
Because the Validate()
method signature returns IEnumerable<>
, that yield return can be used to lazily generate the results - this is beneficial if some of the validation checks are IO or CPU intensive.
public IEnumerable Validate(ValidationContext validationContext)
{
if (this.Enable)
{
// ...
if (this.Prop1 > this.Prop2)
{
yield return new ValidationResult("Prop1 must be larger than Prop2");
}
Also, if you are using MVC ModelState
, you can convert the validation result failures to ModelState
entries as follows (this might be useful if you are doing the validation in a custom model binder):
var resultsGroupedByMembers = validationResults
.SelectMany(vr => vr.MemberNames
.Select(mn => new { MemberName = mn ?? "",
Error = vr.ErrorMessage }))
.GroupBy(x => x.MemberName);
foreach (var member in resultsGroupedByMembers)
{
ModelState.AddModelError(
member.Key,
string.Join(". ", member.Select(m => m.Error)));
}