Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
950 views
in Technique[技术] by (71.8m points)

validation - JSF custom validator not invoked when submitted input value is null

I created a custom validator which is not getting called when input is null.

My validator code:

@FacesValidator("requiredValidator")
public class RequredValidation implements Validator {

    public void validate(FacesContext context, UIComponent component,
            Object value) throws ValidatorException {
        System.out.println("in valid GGGGGGGG");

    }

My xhtml page code:

<p:message for="urlInput"  />

<p:inputText id="urlInputv" value="#{coverageBean.firstname}" label="URL" maxlength="2" >
    <f:validator validatorId="requiredValidator"></f:validator>
</p:inputText>
<p:message for="urlInputv"  />
<p:commandButton value="submit" action="#{loginBean.validateText}" />

Now this is working when I am entering any value in text box, but it is not working when inputtext is null.

The server is using

  • Tomcat
  • primefaces 3.5
  • jsf2.0

Please could anyone tell what the problem is?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

By default, JSF does not validate an empty submitted value if Bean Validation (JSR303) is not available in the environment. This behavior can be controlled with the context parameter javax.faces.VALIDATE_EMPTY_FIELDS.

The default value for javax.faces.VALIDATE_EMPTY_FIELDS is auto, meaning that empty fields are validated if Bean Validation (JSR303) is available in the class path.

If you want to validate empty fields anyway without Bean Validation, then explicitly set the context parameter in your web.xml to true like this:

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

It must be said that you normally use required="true" in case you want to validate an input field as required. You don't need to perform that job in your custom validator then.

<p:inputText ... required="true" requiredMessage="Please enter value" />

Or, more abstract with <f:validateRequired>:

<p:inputText ... requiredMessage="Please enter value">
    <f:validateRequired />
</p:inputText>

Do note that you can safely use multiple validators on the very same input component.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...