How to do validation in JSF, how to create a custom validator in JSF

I would like to test 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 find out more about this?

+6
source share
1 answer

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!")); } } } 

@FacesValidator register it in JSF with myValidator ID so you can use it like this:

 <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 validators to the same component:

 <h:inputText id="foo" value="#{bean.foo}"> <f:validator validatorId="myValidator" /> </h:inputText> <h:message for="foo" /> 

Whenever a validator throws a ValidatorException , its message will be displayed in the <h:message> associated with the input field.

To take another step, you can use the JSR303 bean check. This checks the fields based on annotations. Since this will be the whole story, here are just some links to get you started:

<f:validateBean> is useful if you want to test to disable the JSR303 bean. Then you put the input components (or even the whole form) inside <f:validateBean disabled="true"> .

See also:

+12
source

Source: https://habr.com/ru/post/888446/


All Articles