开发者

Shouldn't the validation be skipped when there is no value specified?

I'm using JSF2 on GlassFish 3.

I have a form that accepts and optional phone number. I have this custom phone number validator (below), and I have the field set to required="false" because the phone number is optional in the form.

The problem is, the value in the field is always getting validated. Shouldn't the validation be skipped when there is no value specified?

There must be something I'm doing wrong. Any help is appreciated, thanks!

<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 {

        St开发者_如何学Goring 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);
        }
    }

}


From JSF 2.0 on, JSF will by default validate empty fields as well in order to play well with the new Java EE 6 provided JSR 303 Bean Validation API which offers among others @NotNull and on.

There are basically two ways to go around this:

  1. Tell JSF to not validate empty fields by the following entry in web.xml.

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

    The disadvantage is obvious: you can't utilize JSR 303 Bean Validation at its full powers anymore.


  2. Do a nullcheck yourself in the Validator.

    if (object == null) return;
    

    If you don't have a javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL context param which is set to true, then you'd like to cast to String and check isEmpty() as well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜