I would like to perform validation in some of my input components such as <h:inputText> using some Java bean method. Should I use <f:validator> or <f:validateBean> for this? Where can I read more about it?
You just 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!"));
}
}
}
The @FacesValidator will register it to JSF with validator ID myValidator so that you can reference it in validator attribute of any <h:inputXxx>/<h:selectXxx> component as follows:
<h:inputText id="foo" value="#{bean.foo}" validator="myValidator" />
<h:message for="foo" />
You can also use <f:validator>, which would be the only way if you intend to attach multiple validator on the same component:
<h:inputText id="foo" value="#{bean.foo}">
<f:validator validatorId="myValidator" />
</h:inputText>
<h:message for="foo" />
Whenever the validator throws a ValidatorException, then its message will be displayed in the <h:message> associated with the input field.
You can use <f:validator binding> to reference a concrete validator instance somewhere in the EL scope, which in turn can easily be supplied 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 get a step further, you can use JSR303 bean validation. This validates fields based on annotations. Since it's going to be a whole story, here are just some links to get started:
The <f:validateBean> is only useful if you intend to disable JSR303 bean validation. You then put the input components (or even the whole form) inside <f:validateBean disabled="true">.
See also:
来源:https://stackoverflow.com/questions/6047866/how-to-perform-validation-in-jsf-how-to-create-a-custom-validator-in-jsf