2013-04-03 57 views
2

我正在使用JSF 2.0並希望將我自定義的RangeValidator附加到HtmlInputText。在我的支持bean中,有一個創建HTMLInputText的代碼片段。如果我添加一個默認的驗證器,我的代碼就像預期的那樣工作。如果我以相同的方式添加自定義RangeValidator(通過使用FacesContext ...),則會出現錯誤,更確切地說,是一個「未知ID」錯誤。如果我使用new關鍵字創建一個實例,似乎我無法使用我的訪問器方法,更確切地說,我的HtmlInputText在運行時會使用新創建的RangeValidator實例,所以屬性值最小爲0和最大值= 0,我的驗證器是無用的。我怎樣才能讓我的自定義驗證器工作?提前致謝。如何將自定義的jsf-validators綁定到編程創建的HTML元素?

// Snippet which creates HTML-Components 
if ((integerField.getMaximalValue() != null) && (integerField.getMinimalValue() != null)) { // serverside validation required 
    // Default JSF Validator - works! 
    // final LongRangeValidator validator = (LongRangeValidator) FacesContext.getCurrentInstance().getApplication().createValidator(LongRangeValidator.VALIDATOR_ID); 
    // CustomValidator - ERROR: Unknown validator id; 
    final RangeValidator validator = (RangeValidator) FacesContext.getCurrentInstance().getApplication().createValidator("mypackage.validators.RangeValidator"); 
    // construct custom validator instance - not working, seems to be a different instance! 
    // RangeValidator validator = new RangeValidator(); 
    validator.setMaximum(integerField.getMaximalValue()); 
    validator.setMinimum(integerField.getMinimalValue());  
    inputInteger.addValidator(validator); 
} 

// Validator 
@FacesValidator("RangeValidator") 
public class RangeValidator implements Validator { 
    private int minimum; 
    private int maximum; 
    @Override 
    public void validate(FacesContext context, UIComponent uiComponent, Object value) throws ValidatorException { 
     //System.out.println("RangeValidator.validate: " + value); 
     int val = Integer.parseInt((String) value); 
     if ((val <= this.getMaximum()) && (val >= this.getMinimum())){ 
      // ok 
     } else { 
      FacesMessage fm = new FacesMessage(); 
      String message = "Das Feld " + uiComponent.getClientId() + " liefert Validierungsfehler!"; 
      fm.setSeverity(FacesMessage.SEVERITY_ERROR); 
      fm.setSummary(message); 
      fm.setDetail(message); 
      throw new ValidatorException(fm); 
     } 
    } 
    // Accessors 
    ... 
} 

回答

1

我找到了解決問題的辦法:RangeValidator控件需要實現Serializable接口,以及所有會像預期;

相關問題