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

独自空忆成欢 提交于 2019-11-26 04:00:39

问题


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?


回答1:


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:

  • Hibernate Validator - Getting started
  • JSF 2.0 tutorial - Finetuning validation

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:

  • JSF doesn't support cross-field validation, is there a workaround?
  • How to perform JSF validation in actionListener or action method?


来源:https://stackoverflow.com/questions/6047866/how-to-perform-validation-in-jsf-how-to-create-a-custom-validator-in-jsf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!