View Source

h1. How to Use Validators

Validators verify data is within parameters specified by the developer.

----
\\
{panel}This tutorial will discuss the following topics:

* [Standard JSF Validation|#jsf]
* [Application Level Validation|#application]
* [Custom Validator|#custom]
* [Custom Validator Methods in Backing Beans|#bean]
* [Single / Partial Submit|#partialsubmit]
* [Tutorial Source Code Downloads|#downloads]

{panel}
\\
----

h3. {anchor:jsf}Standard JSF Validation
\\
Standard JSF validation uses h:message and/or h:messages tags to output validation failure messages in response to failed validation when executing the JSF lifecycle.

The _required_ attribute is available on JSF input tags. There are also three types of validators that come with JSF:

* *f:validateLength* -- checks whether the local value of a component is within a certain range. The value must be a String.
* *f:validateLongRange* -- checks whether the local value of a component is within a certain range. The value must be any numeric type or String that can be converted to a long.
* *f:validateDoubleRange* -- checks whether the local value of a component is within a certain range. The value must be a floating point, or be convertable to a floating point.

In our demo, a bean named user has been defined in the faces.config file as a session scope bean. The ice:inputText component will take the user's age. If you attempt to input an age that is less than 1 or greater than 120 you will get the standard JSF error message.

The following is the basic code snippet used for the standard validation:

{code:xml}
<!-- age validator -->
<ice:inputText id="age" value="#{user.age}">
<f:validateLongRange maximum="120" minimum="1"/>
</ice:inputText>
<ice:message style="color: red;" id="ageError" for="age"/>
{code}
\\
\\
----

h3. {anchor:application}Application Level Validation
\\
Application level validation is performed in the backing bean (usually the action method binding).

In the following example, the user clicks the 'Register' button which calls the register() method. If our application level validation fails, we can manually construct a FacesMessage in our bean code and display it via the ice:message tag in our page:

{code:title=bean|borderStyle=solid}
public String register(){
FacesContext context = FacesContext.getCurrentInstance();
if(StringUtils.isEmpty(user.getName())){
FacesMessage message = new FacesMessage();
message.setSeverity(FacesMessage.SEVERITY_ERROR);
message.setSummary("Name Field is Blank");
message.setDetail("Name Field is Blank..");
context.addMessage("tutorialForm:name",message);
return "error"
}
return "success"
}
{code}
\\
\\
----

h3. {anchor:custom}Custom Validator
\\
Creating a custom validator requires four steps:

# Create a class that implements the Validator interface
# Implement the validate() method
# Register your custom validator in faces.config
# Use the <f:validator/> tag in your page

h5. Implement the Validator interface

{code:title=PhoneNumberValidator.java|borderStyle=solid}
public class PhoneNumberValidator implements Validator{
/** phone number in form of xxx-xxxx*/
private static final String PHONE_NUM = "[0-9]{3}[-]{1}[0-9]{4}";

...
}
{code}

h5. Implement the validate() method

{code:title=PhoneNumberValidator.java|borderStyle=solid}
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException{

/* create a mask*/
Pattern mask = Pattern.compile(PHONE_NUM);

/* retrieve the string value of the field*/
String phoneNumber = (String)value;

/*check to ensure that the value is a phone number*/
Matcher matcher = mask.matcher(phoneNumber);

if(!matcher.matches()){

FacesMessqage msg = new FacesMessage();
message.setDetail(" Phone number not in valid format");
message.setSumamry("Phone number not in valid format");
message.setSeverity(FacesMessage.SEVEROTY_ERROR);
throw new ValidatorException(message);
}
}
{code}

h5. Register the Validator in faces.config

{code:xml}
<validator>
<validator-id>phoneNumberValidator</validator-id>
<validator-class>com.icesoft.icefaces.tutorial.validators.custom.PhoneNumberValidator</validator-class>
</validator>
}
{code}

h5. Use the Tag in your Page

{code:xml}
<ice:inputText id=phoneNumber value="#{user.phoneNumber}">
<f:validator validatorId="phoneNumberValidator"/>
</ice:inputText>
{code}
\\
\\
----

h3. {anchor:bean}Custom Validator in Backing Beans
\\
Instead of having a separate Validator class, you can also set up custom validator methods within your backing bean:

{code:title=backing bean|borderStyle=solid}
public void validateEmail(FacesContext context, UIComponent validate, Object value){
String email = (String)value;

if(email.indexOf('@')==-1){
((UIInput)validate).setValid(false);
FacesMessage msg = new FacesMessage("Invalid Email");
context.addMessage(validate.getClientId(context), msg);
}
}
{code}

Tag usage:

{code:xml}
<ice:inputText id="email" value="#{user.email}" validator="#{user.validateEmail}" required="true"/>
{code}
\\
\\
----

h3. {anchor:partialsubmit}Single Submit (ICEfaces 2) / Partial Submit (ICEfaces 1)
\\
ICEfaces _singleSubmit_ uses AJAX to show a component's validation error message as soon as the focus is off the component (not just when a form is submitted). This allows for 'real-time' validation without having to submit the form for validation.

{code:title=ICEfaces 2 Single Submit Applied to Form Elements}
<h:form>
<icecore:singleSubmit />
<ice:inputText id="age" value="#{user.age}" >
<f:validateLongRange maximum="120" minimum="1"/>
</ice:inputText>
</h:form>
{code}

{code:title=ICEfaces 1 Partial Submit Attribute}
<ice:inputText id="age" value="#{user.age}" partialSubmit="true">
<f:validateLongRange maximum="120" minimum="1"/>
</ice:inputText>
{code}
\\
\\
----

h3. {anchor:downloads}Tutorial Source Code Downloads
\\
|| Example || Source || Notes ||
| validators-standard |[validators-standard source code |^validators-standard.zip|Download Source Code]| Simple example of how to setup standard validators. |
| validators-custom |[validators-custom source code |^validators-custom.zip|Download Source Code]| Demonstration of how to setup custom validators. |
| validators-backing-bean |[validators-backing-bean source code |^validators-backing-bean.zip|Download Source Code]| Example showing to set up a validator in the backing bean. |
| validators-app-level |[validators-app-level source code |^validators-app-level.zip|Download Source Code]| This example explains how to set up validators at the application level. |