Validators

Table of Contents

How to Use Validators

Validators verify data is within parameters specified by the developer.





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:

<!-- 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"/>




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:

bean
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"
}




Custom Validator


Creating a custom validator requires four steps:

  1. Create a class that implements the Validator interface
  2. Implement the validate() method
  3. Register your custom validator in faces.config
  4. Use the <f:validator/> tag in your page
Implement the Validator interface
PhoneNumberValidator.java
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}";

    ...
}
Implement the validate() method
PhoneNumberValidator.java
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);
    }
}
Register the Validator in faces.config
<validator>
    <validator-id>phoneNumberValidator</validator-id>
    <validator-class>com.icesoft.icefaces.tutorial.validators.custom.PhoneNumberValidator</validator-class>
</validator>
}
Use the Tag in your Page
<ice:inputText id=phoneNumber value="#{user.phoneNumber}">
    <f:validator validatorId="phoneNumberValidator"/>
</ice:inputText>




Custom Validator in Backing Beans


Instead of having a separate Validator class, you can also set up custom validator methods within your backing bean:

backing bean
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);
    }
}

Tag usage:

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




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.

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>
ICEfaces 1 Partial Submit Attribute
<ice:inputText id="age" value="#{user.age}" partialSubmit="true">
    <f:validateLongRange maximum="120" minimum="1"/>
</ice:inputText>




Tutorial Source Code Downloads


Example Source Notes
validators-standard validators-standard source code Simple example of how to setup standard validators.
validators-custom validators-custom source code Demonstration of how to setup custom validators.
validators-backing-bean validators-backing-bean source code Example showing to set up a validator in the backing bean.
validators-app-level validators-app-level source code This example explains how to set up validators at the application level.
Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.

© Copyright 2018 ICEsoft Technologies Canada Corp.