How to perform validation in JSF and how to create a custom validator in JSF
I want to perform validation in some of my input components, such as < H: inputtext > using some java bean methods Should I use < F: validator > or < F: validatebean > for this? Where can I read more about it?
Solution
You only need to implement the validator interface
@FacesValidator("myValidator") public class MyValidator implements Validator { @Override public void validate(FacesContext context,UIComponent component,Object value) throws ValidatorException { // ... if (valueIsInvalid) { throw new ValidatorException(new FacesMessage("Value is invalid!")); } } }
@Facesvalidator will register it with JSF using the verifier ID myvalidator so that you can reference it in any verifier attribute of < H: inputxxx > / < H: selectxxx > The components are as follows:
<h:inputText id="foo" value="#{bean.foo}" validator="myValidator" /> <h:message for="foo" />
You can also use < F: validator >, which is the only way to attach multiple validators to the same component:
<h:inputText id="foo" value="#{bean.foo}"> <f:validator validatorId="myValidator" /> </h:inputText> <h:message for="foo" />
Whenever the validatorexception is thrown by the validator, its message will be displayed in < H: Message > Associated with an input field
You can use < F: validator binding > to reference a specific validator instance somewhere within the El range, which in turn can be easily provided as a lambda:
<h:inputText id="foo" value="#{bean.foo}"> <f:validator binding="#{bean.validator}" /> </h:inputText> <h:message for="foo" />
public Validator getValidator() { return (context,component,value) -> { // ... if (valueIsInvalid) { throw new ValidatorException(new FacesMessage("Value is invalid!")); } }; }
To go further, you can use JSR 303 bean validation This validates the field against the comments As this will be a complete story, here are just some getting started links:
> Hibernate Validator – Getting started > JSF 2.0 tutorial – Finetuning validation
< F: validatebean > is only useful if you intend to disable JSR 303 bean validation Then put the input component (or even the whole form) in < F: validatebean disabled = "true" >
You can also see:
> JSF doesn’t support cross-field validation,is there a workaround? > How to perform JSF validation in actionListener or action method?