...
If a class should be a subject to validation it should implement com.cognifide.slice.validation.api.Validatable
. The interface introduces only one method: validate
, which takes one argument: com.cognifide.slice.validation.api.ValidationResultBuilder
. The argument allows you to define a validation messages of different levels. The types levels include:
- error
- warning
- information
If at least one message has been added, the object is considered invalid. If there is no message, the object is considered valid.
An example usage of the interface is shown in the following listing. If the text property, mapped from the resource, is blank, the model is invalid.
Code Block |
---|
import org.apache.commons.lang.StringUtils; import com.cognifide.slice.mapper.annotation.JcrProperty; import com.cognifide.slice.mapper.annotation.SliceResource; import com.cognifide.slice.validation.api.Validatable; import com.cognifide.slice.validation.api.ValidationResultBuilder; @SliceResource public class TextModel implements Validatable { @JcrProperty private String text; @Override public void validate(ValidationResultBuilder result) { if (StringUtils.isBlank(text)) { result.addErrorMessage("Text cannot be empty"); } } public String getText() { return text; } } |
Validator
The actual validation of an object is performed by com.cognifide.slice.validation.api.Validator
interface. It defines one method: validate
, which takes Validatable
object as an argument. In result it It returns ValidationResult
as a result of validation. ValidationResult
should can be used for reading a result of validation and validation messages.
Slice's validation module provides a default implementation of the interface which can be used (injected) in your models to perform validation of objects of different types. Take a look at the example below where the model created by ModelProvider
is validated before use.
Code Block |
---|
import com.cognifide.slice.api.model.InitializableModel; import com.cognifide.slice.api.provider.ModelProvider; import com.cognifide.slice.mapper.annotation.JcrProperty; import com.cognifide.slice.mapper.annotation.SliceResource; import com.cognifide.slice.validation.api.Validator; import com.cognifide.app.components.configuration.image.ImageConfigurationModel; import com.google.inject.Inject; @SliceResource public class ImageModel implements InitializableModel { @JcrProperty private String configPath; private int size; private final ModelProvider modelProvider; private final Validator validator; @Inject public ImageModel(final ModelProvider modelProvider, final Validator validator) { this.modelProvider = modelProvider; this.validator = validator; } @Override public void afterCreated() { ImageConfigurationModel configurationModel = modelProvider.get(ImageConfigurationModel.class, configPath); if (validator.validate(configurationModel).isValid()) { size = configurationModel.getDefaultSize(); } else { ... } } ... } |