2012-05-28 25 views
3

我知道我可以通過UIInput#getValue()獲得舊值。如果值已更改,如何檢入驗證程序?

但在很多情況下,字段綁定到一個bean值我想獲得默認值,我不需要驗證,如果輸入等於默認值。

如果某個字段具有唯一約束且您有編輯表單,這非常有用。
驗證將始終失敗,因爲在檢查約束方法中,它總是會找到自己的值,從而驗證爲false。

一種方法是使用<f:attribute>作爲屬性傳遞該默認值並檢查驗證器內部。但有沒有更簡單的內置方式?

+0

[How to get old value from JSF/ADF validator?](http://stackoverflow.com/questions/2413424/how-to-get-old-value-from-jsf-adf-validator) – djmj

回答

10

提交的值僅在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跳過更新模型值並調用操作階段。

+0

哈哈,當你添加了getValue()方法的時候,我也測試了它,並且想把它寫下來^^。這個解決方案好得多。 – djmj

+0

有時候事情太明顯了,你甚至都沒有看到它;) – BalusC

+0

我甚至在我的問題中有答案?我認爲getValue會始終獲得舊值。對不起,浪費你的時間。 – djmj

相關問題