Jimmy
Jimmy

Reputation: 9815

ASP.NET MVC 2 Model object validation

I'm trying to validate a model object outside of the context of ModelState within a controller, I currently have a parser that creates model objects from an excel file and I want to be able to report how many entries were added to the database and how many failed, is there a way to validate a model object on its data annotations outside of model binding?

I'm looking for something similar to the rails model method of model.valid? or a way for me to implement that myself.

My current solution is just manually checking if a few key fields are present but this duplicates requirements between my model class and its metadata, there has to be a better way to hook into the model validation checking that is done by mvc 2.

Thanks

Upvotes: 3

Views: 586

Answers (1)

Robert Koritnik
Robert Koritnik

Reputation: 105081

You have to use Validator class which can be found as part of DataAnnotations.

User userEntity = new User();

var validationContext = new ValidationContext(userEntity, null, null);
var validationResults = new List<ValidationResult>();
DataAnnotations.Validator.TryValidateObject(userEntity, validationContext, validationResults, true);

In case all your entities or application/domain model classes inherit from the same class, you can put this code in parent class or as an extension method to keep your class clean.

Otherwise you're going to use singleton pattern to create a special static validator. You can use validation results to your liking.

Metadata classes

If you're using metadata classes to define validation rules for your entities, you should register metadata classes prior to validation:

TypeDescriptor.AddProviderTransparent(
    new AssociatedMetadataTypeTypeDescriptionProvider(
        typeof(User),
        typeof(UserMetadata)
    ),
    typeof(User)
);

Validator.TryValidateObject(userEntity, context, results, true);

Upvotes: 2

Related Questions