Arbitrary validation in JSF using validator attribute

Recently I was searching for an example about the arbitrary validation in JSF component, found very minimal examples in the web. Here I would like to share my knowledge on this.

One of the good feature in JSF is creating custom validator. To create a custom validator there two ways available.

a) Create a Validator class and register the class in faces-config.xml file. Then you can start using your custom validator wherever you want. You can find nice example here.

b) There are a few cases where you don’t see re usage of the validation logic, in that case obviously you will look for a simple solution. Fortunately JSF provides “Arbitrary Validation” feature to achieve this. Here are the steps.

1) Step1 – Bind a method expression to validator attribute of input component.

<h:inputText value=”#{userRegistrationBean.username}” required=”true”
validator=”#{userRegistrationBean.validateUsername}” />

2) Step2 – Write the specified validator method in the specified bean.

public class UserRegistrationBean {

public void validateUsername(FacesContext facesContext, UIComponent uiComponent,
Object value) throws ValidatorException {
// perform
if (the validation fails) {
throw new ValidatorException(new FacesMessage(“Invalid Username”));

Hope the above example helps you, let me know if you have further questions on this.

5 Responses to Arbitrary validation in JSF using validator attribute

  1. newaz123 says:

    Do you know that the validator attribute does not work with Google chrome browser.

  2. Venkat says:

    validator attribute does the validation at server side not in client side. Please test your code with other browser.

  3. SriKanth says:

    I wanna to know how to validate using validator tag with Managed Bean method, for me the code that is on the website is not working with netbeans 6.1 IDE.

    Let me know in Detail

    Yours Sincerey,
    S G Srikanth

  4. Venkat says:

    What is the error are you getting?

  5. short url says:

    Hello, i read yyour blog occasionally and i own a similar one and i was juat wondering
    if you get a lot off spam comments? If so how do you prevent it, any plugin or anything you can suggest?
    I get so much lately it’s driving me crazy so
    any assistance is very much appreciated.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: