JSF Tip #10 - The FacesValidator annotation

In the previous blog entry titled "Writing your own validator" you learned how to write a validator and hook it up for validation. At that time we made it all work using the faces-config.xml file. There is however another way, which we will describe below!


    package nohelloworld;

    @FacesValidator(value="NoHelloWorldValidator")
    public class NoHelloWorldValidator implements Validator {
    
        public void validate(FacesContext context,  
            UIComponent component, Object value) throws ValidatorException
            if (value != null && "Hello World".equals(value.toString()) {
                throw new ValidatorException(new FacesMessage( 
                    "Hello World is invalid"));
            } 
        }
    }
        

In the faces-config.xml file you had to define the validator-id and the validator-class to register the validator. When using the annotation the value of the FacesValidator annotation defines the validator-id, and the validator-class is going to be the class that was annotated.

Posted September 17, 2012

Up