Search code examples
silverlightwcf-ria-services

Can Validator.TryValidateObject force [CustomValidation] attributes to validate a property?


I have decorated a property of a class with a CustomValidationAttribute to validate if a GUID value was set but when I try to force it to be executed by using the helper method Validator.TryValidateObject() it seems that it doesn't invoke my validation logic.

The validation logic is being triggered when the value of the decorated property has changed, but I need to handle the scenario wherein the user clicks the save button without filling up required fields, hence the need to force validation attributes to run before a call to DomainContext.SubmitChanges() is called.

Interestingly, even classes that inherit from ValidationAtrribute isn't being run by Validator.TryValidateObject().

What is the correct way to force validation attributes to be executed?


Solution

  • Custom validators applied at the property level will have to be validated separately by using TryValidateProperty.

    e.g.

    Validator.TryValidateProperty(ViewModel.MyProperty,
                    new ValidationContext(ViewModel.MyProperty, null, null) 
                    { MemberName = "MyProperty" }, results);