我在 GlassFish 3 上使用 JSF2。
我有一个接受可选电话号码的表格。我有这个自定义电话号码验证器(如下),并且我将该字段设置为 required="false",因为电话号码在表单中是可选的。
问题是,该领域的价值总是得到验证。当没有指定值时,是否应该跳过验证?
一定是我做错了什么。任何帮助表示赞赏,谢谢!
<h:outputText value="#{msg.profile_otherPhone1Label}#{msg.colon}" />
<h:panelGroup>
<p:inputText label="#{msg.profile_otherPhone1Label}" id="otherPhone1" value="#{profileHandler.profileBean.otherPhone1}" required="false">
<f:validator validatorId="phoneValidator" />
</p:inputText>
<p:spacer width="12"/>
<h:outputText value="#{msg.profile_phoneExample}" />
</h:panelGroup>
#
public class PhoneValidator implements Validator {
@Override
public void validate(FacesContext facesContext, UIComponent uIComponent,
Object object) throws ValidatorException {
String phone = (String) object;
// count the digits; must have at least 9 digits to be a valid phone number
// note: we're not enforcing the format because there can be a lot of variation
int iDigitCount = 0;
for (char c : phone.toCharArray()) {
if (Character.isDigit(c)) {
iDigitCount++;
}
}
if (iDigitCount < 9) {
FacesMessage message = new FacesMessage();
message.setSummary(Messages.getMessage("error_phoneNumberNotValid"));
message.setSeverity(FacesMessage.SEVERITY_ERROR);
throw new ValidatorException(message);
}
}
}
从 JSF 2.0 开始,JSF 默认情况下也会验证空字段,以便与新的 Java EE 6 提供的 JSR 303 Bean 验证 API 良好配合,该 API 提供了其他功能@NotNull and on.
基本上有两种方法可以解决这个问题:
-
通过以下条目告诉 JSF 不要验证空字段web.xml
.
<context-param>
<param-name>javax.faces.VALIDATE_EMPTY_FIELDS</param-name>
<param-value>false</param-value>
</context-param>
缺点很明显:您无法再充分利用 JSR 303 Bean Validation。
-
自己做一个空检查Validator
.
if (object == null) return;
如果你没有javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL
上下文参数设置为true
,那么你想投射到String
并检查isEmpty()
以及。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)