2013-02-09 133 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!">