Validating properties with System.ComponentModel.DataAnnotations.Validator

I have an Entity setting with Data Annotation attributes, and I'm trying to test it using a static Validator , but I get various exceptions, is this not right:

string _ValidateProperty(object instance, string propertyName) { var validationContext = new ValidationContext(instance, null, null); validationContext.MemberName = propertyName; var validationResults = new List<ValidationResult>(); var isValid = Validator.TryValidateProperty(instance, validationContext, validationResults); if (isValid) return string.Empty; return validationResults.FirstOrDefault<ValidationResult>().ErrorMessage; } 
+6
source share
1 answer

You indicated that you are TryValidateProperty Exception , but it looks like you are passing your instance to the TryValidateProperty method when you need to pass the value of this property.

Instead

 Validator.TryValidateProperty(instance, validationContext, validationResults); 

to try

 Validator.TryValidateProperty(propertyValue, validationContext, validationResults); 

you need to pass propertyValue to your method (or use reflection, which will be slower)

eg,

 _ValidateProperty(someObject, "Field1", someObject.Field1); 
+8
source

Source: https://habr.com/ru/post/945969/


All Articles