JSF validators safeguard the application and model from invalid entries. Outputting error messages and giving the UIComponent an invalid state (allowing the field to be marked), skipping update-model and invoke-application phases straight to render response.
There are two major problems with this approach:
- complex validation logic may reside inside domain objects, requiring the model to be updated and the application to be invoked.
- it does not allow for non-fatal validations (aka warnings).
JsfWarn fills this gap allowing the definition of field level warning validators. These are performed prior to the render-response phase towards the end of the JSF life cycle. At this point the model has been updated and the application invoked.
Include the following dependency:
[xml]
<dependency>
<groupId>com.knitelius</groupId>
<artifactId>jsfwarn</artifactId>
<version>0.1.0-beta1</version>
</dependency>
[/xml]
To define a warning validator you simply implement the WarningValidator interface. Alternatively you can use existing JSF validators.
[java]
@Named
public class FooWarningValidator implements WarningValidator{
@Inject
private FooBean fooBean;
@Override
public void process(FacesContext context, UIInput component, ValidationResult validationResult) {
if(!fooBean.isBarValid()) {
validationResult.setFacesMessage(new FacesMessage(FacesMessage.SEVERITY_WARN, "FooBar", "This is a warning."));
}
}
}
[/java]
To utilize this validator simply add the tag library xmlns:jw=”http://knitelius.com/jsfwarn” and add the <jw:warning /> tag to the targeted component.
[xhtml]
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:jw="http://knitelius.com/jsfwarn">
<h:head>
<title>JSF Warning Messages Example</title>
</h:head>
<h:body>
<style>
.myWarningStyle {
…
}
</style>
<h:form>
…
<h:outputLabel for="bar" value="Default warning:" />
<h:inputText id="bar">
<jw:warning styleClass="myWarningStyle" validator="#{fooWarningValidator}" />
<f:ajax event="change" render="@this" />
</h:inputText>
<h:message for="bar" />
…
</h:form>
</h:body>
</html>
[/xhtml]
You can also define inline style.
[xhtml]
<jw:warning validator="#{…}" style="border-color: #090580" />
[/xhtml]
Or severity specific warning styles:
[xhtml]
<jw:warning validator="#{…}" infoClass="myInfoStyle" warnClass="myWarnStyle" />
[/xhtml]