2013-02-09 130 views
0

我有一個JSF驗證器,用於驗證表單中的輸入。驗證器不能正常工作

當我插入簡單的字符串或重複的字符串它正常工作。但是當我沒有輸入任何東西時,正確的信息將會是This field cannot be empty!" : " '" + s + "' is not a valid name!,但我什麼也沒得到。你能幫我找到問題的代碼邏輯?

// Validate Datacenter Name 
    public void validateDatacenterName(FacesContext context, UIComponent component, Object value) throws ValidatorException, SQLException 
    { 

     String l; 
     String s = value.toString().trim(); 

     if (s != null && s.length() > 18) 
     { 
      throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, 
        " Value is too long! (18 digits max)", null)); 
     } 

     try 
     { 
//   l = Long.parseLong(s); 
//   if (l > Integer.MAX_VALUE) 
//   { 
//    throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, 
//      " '" + l + "' is too large!", null)); 
//   } 
     } 
     catch (NumberFormatException nfe) 
     { 
      l = null; 
     } 


     if (s != null) 
     { 

      if (ds == null) 
      { 
       throw new SQLException("Can't get data source"); 
      } 

      Connection conn = null; 
      PreparedStatement ps = null; 
      ResultSet rs; 
      int cnt = 0; 
      try 
      { 
       conn = ds.getConnection(); 
       ps = conn.prepareStatement("SELECT count(1) from COMPONENTSTATS where NAME = ?"); 
       ps.setString(1, s); 
       rs = ps.executeQuery(); 

       while (rs.next()) 
       { 
        cnt = rs.getInt(1); 
       } 

       if (cnt > 0) 
       { 
        throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, 
          " '" + s + "' is already in use!", null)); 
       } 

      } 
      catch (SQLException x) 
      { 
       throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, 
         " SQL error!", null)); 
      } 
      finally 
      { 
       if (ps != null) 
       { 
        ps.close(); 
       } 
       if (conn != null) 
       { 
        conn.close(); 
       } 
      } 
     } 
     else 
     { 
      throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, 
        s.isEmpty() ? " This field cannot be empty!" : " '" + s + "' is not a valid name!", null)); 
     } 

    } 
+1

什麼是 「不正常」 的意思。什麼不工作?你想要你的代碼做什麼?它在做什麼? – Ben 2013-02-09 11:35:26

回答

4

那是因爲你只檢查你是否是!= null。

更改if (s != null)if (s != null && s.lenght() > 0)並再試一次。

順便說一句你String s不能爲空,因爲你

String s = value.toString().trim(); 

初始化,這將導致一個NullPointerException如果你value會是空的。

2

inputText標籤屬性requiredtrue

<h:inputText value="#{backingBean.input}" required="true" 
     requiredMessage="Input is empty!">