我有一个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));
}
}
答案 0 :(得分:4)
这是因为你只检查你是不是!= null。
将if (s != null)
更改为if (s != null && s.lenght() > 0)
,然后重试。
btw你的String s
不能为空,因为你用
String s = value.toString().trim();
如果value
为空,这将导致NullPointerException。
答案 1 :(得分:2)
将inputText
代码属性required
设置为true
<h:inputText value="#{backingBean.input}" required="true"
requiredMessage="Input is empty!">