Validate object instances
Describes how to validate object instances.
The validation service implements the EPiServer.Validation.IValidationService interface to validate object instances. Retrieve the service instance from the IoC container. The service has a single method: IEnumerable<ValidationError> Validate(object instance);.
NoteIn CMS 13, validators must be explicitly registered using dependency injection. Register validators with
services.AddCmsValidator<T>()in the application startup.
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
Create a class that implements the EPiServer.Validation.IValidate<T> interface, which has a single method defined as: IEnumerable<ValidationError> Validate(T instance);.
In CMS 13, validators must be explicitly registered using dependency injection. The validation service locates classes that implement the interface during initialization. When EPiServer.Validation.IValidationService validates an object instance, it calls each validator to which the object instance is assignable. Implement a validator for an interface or a base class, and that validator is called whenever an object that implements or inherits the registered type is validated.
IContentSaveValidate<TContent>
To validate content only during save operations, implement IContentSaveValidate<TContent>. This interface extends IValidate<T> and adds contextual information, such as which SaveAction was used.
NoteValidation timing has changed in CMS 13.
ValidationAttributeimplementations are triggered during content creation scenarios such as inline block creation inContentArea. UseIContentSaveValidate<TContent>when validation depends on the save action or runs only during save operations.
DataAnnotationsValidator
Use the EPiServer.Validation.DataAnnotationsValidator<T> base class when implementing a validator that validates against attributes that inherit System.ComponentModel.DataAnnotations.ValidationAttribute.
Content validation
EPiServer.IContentRepository.Save validates a content instance before saving 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.
Prevent validation by using the save action EPiServer.DataAccess.SaveAction.SkipValidation flag during save. The following example assumes an instance of EPiServer.IContentRepository was retrieved from the IoC container and assigned to the variable contentRepository:
contentRepository.Save(page, SaveAction.Publish | SaveAction.SkipValidation);
Updated 18 days ago
