Arbitrary validation in JSF using validator attribute
August 12, 2008 5 Comments
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.
Do you know that the validator attribute does not work with Google chrome browser.
validator attribute does the validation at server side not in client side. Please test your code with other browser.
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
What is the error are you getting?
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.