【发布时间】:2011-08-13 23:03:14
【问题描述】:
我有一个包含两个输入字段的表单,必须一起验证。我用这个BalusC tutorial 作为起点。
要求是一个逻辑异或:其中一个字段必须填写,但不能同时填写。
这适用于除此之外的所有情况:
1) 填写第一个字段,让第二个空白
2) 移至下一页(值已保存)
3) 返回第一页,删除第一个字段并填写第二个字段。
然后我从验证器收到错误消息(“不要填写两个字段”),尽管我删除了第一个。
代码如下:
<h:inputText id="bbvol" size="10" value="#{a6.behandlungsvolumen.wert}"
required="#{empty param['Laborwerte:pvol']}">
<f:convertNumber locale="de"/>
</h:inputText>
<h:inputText id="pvol" size="10" value="#{a6.plasmavolumen.wert}"
required="#{empty param['Laborwerte:bbvol']}">
<f:convertNumber locale="de"/>
<f:validator validatorId="volumeValidator" for="pvol"/>
<f:attribute name="bbv_value" value="Laborwerte:bbvol" />
</h:inputText>
体积验证器:
public class VolumeValidator implements Validator {
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
// Obtain the client ID of the first volume field from f:attribute.
String bbvolID = (String) component.getAttributes().get("bbv_value");
// Find the actual JSF component for the client ID.
UIInput bbvolInput = (UIInput) context.getViewRoot().findComponent(bbvolID);
// Get its value, the entered value of the first field.
Number bbvol = (Number) bbvolInput.getValue();
// Get the value of the second field
Number pvol = (Number) value;
// Check if only one of the fields is set
if (bbvol != null && pvol != null) {
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Do not fill both fields!", null));
}
}
}
调试此案例表明该行
Number bbvol = (Number) bbvolInput.getValue();
仍然保留旧值而不是新值。
我尝试使用getSubmittedValue() 而不是getValue() 并且这可行。但是这个方法的 javadoc 说:
此方法只能由 decode() 和 validate() 方法 组件,或其对应的 渲染器。
我不确定我是否可以使用此方法而不会在以后遇到问题。
所以我的问题是:
这个问题的原因是什么?
使用getSubmittedValue() 代替getValue() 是一个真正的解决方案吗?
【问题讨论】:
标签: validation jsf jsf-2