The ICEfaces Tutorial
Table of Contents


Lesson: Using the Validator component

How to Use Validators

The validator component is used to verify that certain data is within the specified parameters set by the developer. There are 3 different types of validators:

These will be explained in a bit.

This tutorial will also discuss the four forms of Validation:

As well as sections on:

First, we will explain the three types of validators.

Built-In Validation(Standard)

With the built-in validation(or standard validation) it uses the default JSF validation messages which is good for fast validation, but may lack in terms of being specific to your applicaiton. For this you may want to use custom validation which is discussed later on.

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 users 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.

In the demo, we have added an ice:outputText component at the bottom, to show the age you input.

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


        

Download the Demo:

Application Level Validation

This type of validation is a little more custom than the standard validation. With this type of validation, the message and validation is actually done in one of the methods in the backing bean(usually the action method).

eg. The user clicks the 'Register' button which uses the register() method.

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


        

Download the Demo:

Custom Validation Components

Four Steps:

  • 1) Create a class that implements the Validator interface
  • 2) Implement the validate() method
  • 3) Register your custom validator in the faces.config
  • 4) Use the <f:validator/> tag in your JSP's
  • Implement the Validator interface
        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
            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 the 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 JSP
            <ice:inputText id=phoneNumber value="#{user.phoneNumber}">
                <f:validator validatorId="phoneNumberValidator"/>
            </ice:inputText>
            

    Download the Demo:

    Validation in Backing Beans

    Instead of having a seperate validator class, you can also set up custom validator methods within your backing bean. eg.

        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);
            }
        }
            
    JSP Tag
        <ice:inputText id="email" value="#{user.email}" validator="#{user.validateEmail}" required="true"/>
            

    Download the demo:

    Messages

    All of the above demos include a message of some sorts needing to tie into the page from the backing bean. Below is a simple eg. from the Backing Bean Validator demo on how the messages were implemented.

    Backing Bean Code
                 if(email.indexOf('@')==-1){
                ((UIInput)validate).setValid(false);
                FacesMessage msg = new FacesMessage("Invalid Email");
                context.addMessage(validate.getClientId(context), msg);
                }
    
    
            
    JSP Tag
                <ice:inputText id="email" value="#{user.email}" validator="#{user.validateEmail}" required="true"/>
    
                    <ice:message id="emailError" for="email"/>
            

    The message tag comes AFTER the component you want to tie it to, with a 'for' reference to the components id.

    Partial Submit

    In the code for the Standard(or Built-In) Validation demo, we implemented the partialSubmit. This allows for the error message to be see as soon as the focus is off the inputText component, not just when the submit button is clicked. This allows for 'real-time' validation without having to submit the form to check if everything valid. We implemented this simply by adding a partialSubmit attribute to the ice: inputText. As shown below:

                 <ice:inputText id="age" value="#{user.age}" partialSubmit="true">
                        <f:validateLongRange maximum="120" minimum="1"/>
                    </ice:inputText>
            

    Examples Using Panel Tabsets

    Example Source Notes
    WebMC Available on the demo site Validators are integrated into the fields for email and password.
    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.

    The ICEfaces Tutorial
    Table of Contents

    Copyright 2006 ICEsoft Technologies Inc. All rights reserved.