【问题标题】:How to check in a Validator if the value has been changed?如果值已更改,如何签入验证器?
【发布时间】:2012-05-28 17:58:41
【问题描述】:

我知道我可以通过UIInput#getValue() 获取旧值。

但在许多情况下,当字段绑定到 bean 值时,我希望获得默认值,如果输入等于默认值,我不需要验证。

如果某个字段具有唯一约束并且您有一个编辑表单,这将非常有用。
验证总是会失败,因为在检查约束方法中它总是会找到自己的值,从而验证为假。

一种方法是使用<f:attribute> 将该默认值作为属性传递并检查验证器内部。但是有没有更简单的内置方法?

【问题讨论】:

标签: validation jsf default-value


【解决方案1】:

提交的值在validate() 实现中仅作为value 参数可用。

public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
    Object oldValue = ((UIInput) component).getValue();

    if (value != null ? value.equals(oldValue) : oldValue == null) {
        // Value has not changed.
        return;
    }

    // Continue validation here.
}

另一种方法是将Validator 设计为ValueChangeListener。只有当值真正改变时才会调用它。它有点 hacky,但它可以完成你真正需要的工作。

<h:inputText ... valueChangeListener="#{uniqueValueValidator}" />

<h:inputText ...>
    <f:valueChangeListener binding="#{uniqueValueValidator}" />
</h:inputText>

@ManagedBean
public class UniqueValueValidator implements ValueChangeListener {

    @Override
    public void processValueChange(ValueChangeEvent event) throws AbortProcessingException {
        FacesContext context = FacesContext.getCurrentInstance();
        UIInput input = (UIInput) event.getComponent();
        Object oldValue = event.getOldValue();
        Object newValue = event.getNewValue();

        // Validate newValue here against DB or something.
        // ...

        if (invalid) {
            input.setValid(false);
            context.validationFailed();
            context.addMessage(input.getClientId(context),
                new FacesMessage(FacesMessage.SEVERITY_ERROR, "Please enter unique value", null));
        }
    }

}

请注意,您不能在那里抛出ValidatorException,这就是为什么需要手动将组件和面孔上下文设置为无效并手动为组件添加消息的原因。 context.validationFailed() 将强制 JSF 跳过更新模型值并调用操作阶段。

【讨论】:

  • 哈哈,虽然你添加了getValue()方法,但我也测试了它,想写下来^^。这个解决方案要好得多。
  • 有时候事情太明显了,你甚至一时都看不到;)
  • 我什至在我的问题中有答案?我认为 getValue 将始终获得旧值。很抱歉浪费您的时间。
  • 你好。我遵循了这一点,但由于某种原因,如果我去另一个领域,它会一直吸引注意力。我该如何解决这个问题?
  • stackoverflow 和 BalusC,不断给予的礼物!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-16
  • 2018-04-17
  • 1970-01-01
相关资源
最近更新 更多