如果没有指定值,是否应该跳过验证?

Rob*_*ume 8 validation jsf jsf-2

我在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>
Run Code Online (Sandbox Code Playgroud)

#

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);
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

Bal*_*usC 23

从JSF 2.0开始,JSF将默认验证空字段,以便与新的Java EE 6提供的JSR 303 Bean Validation API一起使用,该API提供了其他@NotNull功能.

基本上有两种方法可以解决这个问题:

  1. 告诉JSF不要通过以下条目验证空字段web.xml.

    <context-param>
        <param-name>javax.faces.VALIDATE_EMPTY_FIELDS</param-name>
        <param-value>false</param-value>
    </context-param>
    
    Run Code Online (Sandbox Code Playgroud)

    缺点是显而易见的:您不能再以全功率使用JSR 303 Bean Validation.


  2. 在自己做一个nullcheck Validator.

    if (object == null) return;
    
    Run Code Online (Sandbox Code Playgroud)

    如果你没有设置的javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL上下文参数true,那么你也想要转换String并检查isEmpty().