如何在JSF中执行验证,如何在JSF中创建自定义验证器

我想在我的一些输入组件中执行验证,例如< h:inputText>使用一些 Java bean方法.我应该使用< f:validator>或< f:validateBean>为了这?我在哪里可以阅读更多相关信息?

解决方法

您只需要实现 Validator接口.
@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将使用验证器ID myValidator将其注册到JSF,以便您可以在任何< h:inputXxx> /< h:selectXxx>的验证器属性中引用它.组件如下:

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

您还可以使用< f:validator>,如果您打算在同一组件上附加多个验证器,这将是唯一的方法

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

只要验证器抛出ValidatorException,它的消息就会显示在< h:message>中.与输入字段相关联.

您可以使用< f:validator binding>在EL范围内的某处引用一个具体的验证器实例,这反过来可以很容易地作为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!"));
        }
    };
}

为了更进一步,您可以使用JSR303 bean验证.这将根据注释验证字段.由于这将是一个完整的故事,这里只是一些入门链接

> Hibernate Validator – Getting started
> JSF 2.0 tutorial – Finetuning validation

< f:validateBean>仅在您打算禁用JSR303 bean验证时才有用.然后将输入组件(甚至整个表单)放在< f:validateBean disabled =“true”>中.

也可以看看:

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

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...