...
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 {
...
}
}
...
} |
Validation tag
To render a validation message to an end-user (author), you need to use a dedicated JSP tag - validate tag defined in the http://cognifide.com/jsp/slice/validation taglib. The example below shows an simple usage of it.
Code Block |
---|
language | html/xml |
---|
linenumbers | true |
---|
|
<%@page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"
%><%@include file="/apps/myapp/core/global.jsp"
%><slice:lookup var="model" type="<%=com.cognifide.myapp.components.richtext.TextModel.class%>"/>
<sv:validate object="${model}">
${model.text}
</sv:validate> |
The taglib is registered under sv
prefix. The TextModel object (obtained using <slice:lookup>
tag) is validated in line 4. If the object is valid, the body of the validation tag will be rendered. Otherwise, error message will be output in the following format:
Code Block |
---|
|
<div class="validationMessages">
<div class="title">
title <!-- only if defined -->
</div>
<ul class="errorMessages"> <!-- if error-level messages available -->
<li>Text cannot be empty</li>
<!-- stack trace --> <!-- if stack trace for the message is available, it is printed in HTML comment -->
</ul>
<ul class="warningMessages"> <!-- if warning-level messages available -->
<li>Some warning</li>
<!-- stack trace --> <!-- if stack trace for the message is available, it is printed in HTML comment -->
</ul>
<ul class="informationMessages"> <!-- if information-level messages available -->
<li>Some information</li>
<!-- stack trace --> <!-- if stack trace for the message is available, it is printed in HTML comment -->
</ul>
</div>
<div style="clear:both;font-size:1px"> </div> |
Such format allows you to style them appropriately.
Blank values approach