Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating Properties with System.ComponentModel.DataAnnotations.Validator

Tags:

c#

.net

wpf

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;
        }
like image 427
Ibrahim Najjar Avatar asked May 27 '13 23:05

Ibrahim Najjar


People also ask

How do you validate model data using DataAnnotations attributes?

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.

How do I use system ComponentModel DataAnnotations?

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.

Which static class from the system ComponentModel DataAnnotations namespace can be used to validate objects properties and methods?

ValidationAttribute Class (System. ComponentModel. DataAnnotations) Serves as the base class for all validation attributes.

What is property validation attribute?

Validates that a property value falls within a specified range. Built-in. RegularExpression. Validates that a property value matches a specified regular expression.


1 Answers

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);
like image 152
wal Avatar answered Oct 26 '22 15:10

wal