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

时间:2011-05-24 16:49:44

标签: jsf jsf-2 validation

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

}

1 个答案:

答案 0 :(得分:23)

从JSF 2.0开始,JSF将默认验证空字段,以便与新的Java EE 6提供的JSR 303 Bean Validation API一起使用,该API提供@NotNull以及其他。{/ p>

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

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

    <context-param>
        <param-name>javax.faces.VALIDATE_EMPTY_FIELDS</param-name>
        <param-value>false</param-value>
    </context-param>
    

    缺点显而易见:您无法再以全功率使用JSR 303 Bean验证。


  2. Validator

    中自行进行null检查
    if (object == null) return;
    

    如果您没有设置为javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL的{​​{1}}上下文参数,那么您希望转换为true并检查String同样。