Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 545
user3515365 Avatar asked Apr 09 '14 13:04

user3515365


1 Answers

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.

like image 129
Michi Avatar answered Nov 08 '22 14:11

Michi