HomeDev GuideRecipesAPI Reference
Dev GuideAPI ReferenceUser GuideLegal TermsGitHubNuGetDev CommunityOptimizely AcademySubmit a ticketLog In
Dev Guide

Validate object instances

Describes how to validate object instances.

The validation service implements the EPiServer.Validation.IValidationService interface to validate object instances. You can retrieve the service instance from the IOC container. The service has a single method: IEnumerable<ValidationError> Validate(object instance);.

The service locates implementations of EPiServer.Validation.IValidate<T> during initialization. When a validation request comes for an object instance, the service checks which registered validators are assigned from the passed-in object, and those validators are then called to perform validation.

IValidate<T> interface

To implement a validator, create a class that implements the EPiServer.Validation.IValidate<T> interface, which has a single method defined as: IEnumerable<ValidationError> Validate(T instance);.

You do not need an explicit registration. The validation service locates classes, that implement the interface, during initialization. When you call EPiServer.Validation.IValidationService to validate an object instance, it calls each validator to which you can assign the object instance. You can implement a validator for an interface or a base class, and then call that validator whenever you validate an object that implements/inherits the registered type.

IContentSaveValidate<TContent> 

To implement a validator that only runs when content is being saved, you can implement IContentSaveValidation, this interface extends IValidate but also adds contextual information, such as which save action was used.

DataAnnotationsValidator

Use the EPiServer.Validation.DataAnnotationsValidator<T> base class when you implement a validator that validates against attributes that inherit System.ComponentModel.DataAnnotations.ValidationAttribute.

Content validation

EPiServer.IContentRepository.Save validates a content instance before it is saved to verify that required properties are set. It also validates the properties of the model class (the class inheriting PageData or BlockData or that implements IContent) against any attributes inheriting from System.ComponentModel.DataAnnotations.ValidationAttribute.

You can prevent validation by using the save action EPiServer.DataAccess.SaveAction.SkipValidation flag during save as follows (here it assumes that an instance of EPiServer.IContentRepository was retrieved from the IOC container and assigned to variable contentRepository):
contentRepository.Save(page, SaveAction.Publish | SaveAction.SkipValidation);