djm*_*jmj 3 validation jsf default-value
我知道我可以通过它获得旧的价值UIInput#getValue()
.
但是在很多情况下,字段绑定到bean值,我想获得默认值,如果输入等于默认值,我不需要验证.
如果某个字段具有唯一约束并且您具有编辑表单,则这非常有用.
验证将始终失败,因为在检查约束方法中它始终会找到自己的值,从而验证为false.
一种方法是使用<f:attribute>
并在验证器内部检查将该默认值作为属性传递.但是有更简单的内置方式吗?
Bal*_*usC 11
提交的值仅作为实现中的value
参数提供validate()
.
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.
}
Run Code Online (Sandbox Code Playgroud)
另一种方法是将其设计Validator
为a ValueChangeListener
.然后只有在值真正改变时才会调用它.这有些笨拙,但它能完成你真正需要的工作.
<h:inputText ... valueChangeListener="#{uniqueValueValidator}" />
Run Code Online (Sandbox Code Playgroud)
要么
<h:inputText ...>
<f:valueChangeListener binding="#{uniqueValueValidator}" />
</h:inputText>
Run Code Online (Sandbox Code Playgroud)
同
@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));
}
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,您无法抛出ValidatorException
,这就是为什么需要手动将组件和faces上下文设置为无效并手动添加组件的消息.这context.validationFailed()
将强制JSF跳过更新模型值并调用操作阶段.