Ryan Buening Ryan Buening - 1 year ago 60
C# Question

Combining FluentValidation and IValidatableObject Errors

Is it possible to run both FluentValidation and IValidatableObject in the same ViewModel? For example if I had the following ViewModel:

public class TestViewModel
{
public Foo Foo { get; set; }
public Bar Bar { get; set; }
}

public class Foo : IValidatableObject
{
public string FooName { get; set; }

public IEnumerable<ValidationResult> Validate(System.ComponentModel.DataAnnotations.ValidationContext validationContext)
{
if (string.IsNullOrEmpty(FooName))
{
yield return new ValidationResult("Required from IValidatableObject", new[] { "FooName" });
}
}
}

[Validator(typeof(BarValidator))]
public class Bar
{
public string BarName { get; set; }
}

public class BarValidator : AbstractValidator<Bar>
{
public BarValidator() {
RuleFor(x => x.BarName).NotNull().WithMessage("Required from FluentValidation");
}
}


Is there a way both
Foo
and
Bar
validations can run and return the results when my Controller calls
ModelState.IsValid
?

Answer Source
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download