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.
I开发者_运维百科nterestingly, 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?
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);
A more simplistic way of doing this is to set the last parameter (validateAllProperties) on TryValidateObject() to true. See the msdn article for more information.
List<ValidationResult> vr = new List<ValidationResult>();
ValidationContext vc = new ValidationContext(viewModel, null, null);
Validator.TryValidateObject(viewModel, vc, vr, true);
精彩评论