Validate object instances
This topic 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 of the registered validators that are assigned from the passed-in object, and those validators are then called to perform validation.
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 calls that validator whenever you validate an object that implements/inherits the registered type.
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 that was used.
EPiServer.Validation.DataAnnotationsValidator<T> base class when you implement a validator that validates against attributes that inherit
EPiServer.IContentRepository.Save validates a content instance before it is saved to verify that required properties are set. It also validates the properties on the model class (the class inheriting
BlockData or that implements
IContent) against any attributes inheriting from
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 has been retrieved from IOC container and assigned to variable
contentRepository.Save(page, SaveAction.Publish | SaveAction.SkipValidation);
Updated about 2 months ago