Nate Zaugg
Nate Zaugg

Reputation: 4218

Custom Validation Not Executing

I have a View Model class in a WPF application that has some very complex validation. I have implemented the IValidatableObject interface to provide the custom validation logic. The problem is that my IEnumerable<ValidationResult> Validate(ValidationContext validationContext) is never called!

Here is the code attempting the validation: Validator.TryValidateObject(RMA, new ValidationContext(RMA, null, null), result);

Any ideas why the Validator object is not calling my custom validation code?

Upvotes: 4

Views: 2600

Answers (1)

Nate Zaugg
Nate Zaugg

Reputation: 4218

The problem was that I was I had [Required] on one of the fields in the custom class and the Validator will not perform custom validation until all data annotation validation has been completed. Removing the [Required] allows the custom validation to execute.

EDIT:

When validating an object, the following process is applied in Validator.ValidateObject:

  1. Validate property-level attributes
  2. If any validators are invalid, abort validation returning the failure(s)
  3. Validate the object-level attributes
  4. If any validators are invalid, abort validation returning the failure(s)
  5. If on the desktop framework and the object implements IValidatableObject, then call its Validate method and return any failure(s)

http://jeffhandley.com/archive/2009/10/16/validator.aspx

Validation will abort at step #2.

Upvotes: 9

Related Questions