我知道我可以通過UIInput#getValue()
獲得舊值。如果值已更改,如何檢入驗證程序?
但在很多情況下,字段綁定到一個bean值我想獲得默認值,我不需要驗證,如果輸入等於默認值。
如果某個字段具有唯一約束且您有編輯表單,這非常有用。
驗證將始終失敗,因爲在檢查約束方法中,它總是會找到自己的值,從而驗證爲false。
一種方法是使用<f:attribute>
作爲屬性傳遞該默認值並檢查驗證器內部。但有沒有更簡單的內置方式?
我知道我可以通過UIInput#getValue()
獲得舊值。如果值已更改,如何檢入驗證程序?
但在很多情況下,字段綁定到一個bean值我想獲得默認值,我不需要驗證,如果輸入等於默認值。
如果某個字段具有唯一約束且您有編輯表單,這非常有用。
驗證將始終失敗,因爲在檢查約束方法中,它總是會找到自己的值,從而驗證爲false。
一種方法是使用<f:attribute>
作爲屬性傳遞該默認值並檢查驗證器內部。但有沒有更簡單的內置方式?
提交的值僅在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
。只有當值真的發生變化時纔會調用它。這有點冒險,但它確實有你需要的工作。
<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跳過更新模型值並調用操作階段。
[How to get old value from JSF/ADF validator?](http://stackoverflow.com/questions/2413424/how-to-get-old-value-from-jsf-adf-validator) – djmj