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

喜欢而已 提交于 2019-12-18 16:47:12

问题


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 {

        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:


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.



来源:https://stackoverflow.com/questions/6113935/shouldnt-the-validation-be-skipped-when-there-is-no-value-specified

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!