asp.net mvc Add ModelState error using IValidatableObject

582 views Asked by At

I saw this nice blog that describes adding conditional validation to a asp.net mvc viewmodel. However I'm not sure how the validation error is added/bound to the specific model's property. I would like the error message to be added to my normal ModelState object so I could show the error like so in my view:

ValidationMessageFor(model => model.FirstName)

I think if I had access the the ModelState object from the ValidateMethod(..) then I could just do:

ModelState.AddModelError("FirstName", "First name is required");

And everthing would work smoothly. I'm trying to add conditional Validation.

Has anyone done this before that could provide some insight? I tried the code in the blog but it seems incomplete.

Thanks!

1

There are 1 answers

0
RayLoveless On

I needed to use an this overload that was missing from the blog as mentioned by Stephen.:

yield return new ValidationResult(".....", new[]{ "Property1" })