Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign ValidationResult to specific field?

I am trying to use IValidatableObject to validate form values with respect to each other. I would like to assign a ValidationResult to a specific field so I can display an error message next to that field.

For example, I may want to have users enter passwords twice, and have validation fail if the 2nd is not equal to the first, then have the error message display next to the second.

However it seems I can only assign errors at the model-level this way; by model-level I mean an error that will display with @Html.ValidationSummary(true), and that isn't tied to a specific model field.

I've examined the declaration for ValidationResult, and I don't see any property or method that looks helpful for this. So -- can anyone either show me a way to assign a ValidationResult to a specific field from within a Validate method of an IValidateableObject, or confirm that it is NOT possible do so?

(NOTE: I am NOT looking for a work-around. PLEASE -- no answers about, for example, filters that takes care of the password example. I only want to know specifically about the limits of IValidateObject.)

like image 707
Faust Avatar asked Dec 20 '11 09:12

Faust


1 Answers

Is possible, ValidationResult has an overload that accept IEnumarable of string, properties to be associated.

An example.

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (Password != PasswordConfirmation)
            yield return new ValidationResult("Password confirmation must match", new[] { "PasswordConfirmation" }); 
    }
like image 163
wnascimento Avatar answered Sep 29 '22 12:09

wnascimento