I have my Entity setup with Data Annotation validation attributes and i am trying to validate it using the static Validator class but i am getting different exceptions, isn't this the right way to do it:
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;
}
ComponentModel. DataAnnotations namespace includes the following validator attributes: Range – Enables you to validate whether the value of a property falls between a specified range of values. RegularExpression – Enables you to validate whether the value of a property matches a specified regular expression pattern.
Data annotations (available as part of the System. ComponentModel. DataAnnotations namespace) are attributes that can be applied to classes or class members to specify the relationship between classes, describe how the data is to be displayed in the UI, and specify validation rules.
ValidationAttribute Class (System. ComponentModel. DataAnnotations) Serves as the base class for all validation attributes.
Validates that a property value falls within a specified range. Built-in. RegularExpression. Validates that a property value matches a specified regular expression.
You havent stated what Exception
you are receiving but it appears you are passing your instance to the TryValidateProperty
method when you should be passing the value of the particular property.
Instead of
Validator.TryValidateProperty(instance, validationContext, validationResults);
try
Validator.TryValidateProperty(propertyValue, validationContext, validationResults);
you will have to pass propertyValue
down to your method (or use reflection which will be slower)
eg
_ValidateProperty(someObject, "Field1", someObject.Field1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With