Michele Mariotti
Michele Mariotti

Reputation: 7459

Empty input value does not triggger @NotNull but it triggers @NotBlank

i have this entity:

import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotBlank;

@Entity
@XmlRootElement
@Table
public class Supplier extends AbstractEntity
{
    @Column
    @NotNull
    private String name;

    @Column
    @NotBlank
    private String representative;

    ...
}

and this jsf form:

<h:form>
    <p:commandButton value="save" action="#{supplierController.create}" ajax="false"/>

    <h:panelGrid columns="3" cellpadding="4">
        <h:outputLabel value="#{bundle['Name']}" for="name"/>
        <p:inputText id="name" value="#{supplierController.value.name}"/>
        <p:message for="name"/>

        <h:outputLabel value="#{bundle['Representative']}" for="representative"/>
        <p:inputText id="representative" value="#{supplierController.value.representative}"/>
        <p:message for="representative"/>
    </h:panelGrid>
</h:form>

so, why is @NotBlank triggered and @NotNull is not?

i'm using mojarra-2.1.3_01 (ships hibernate-validator-4.2.0.Final?) under glassfish-3.1.1

Upvotes: 2

Views: 1364

Answers (1)

BalusC
BalusC

Reputation: 1108722

Due to the nature of HTTP, empty request parameters are retrieved as empty string instead of null. So the @NotNull validator will never be triggered. It will only be triggered when the field is missing in the form or when it is disabled.

You can however configure JSF 2.x to interpret empty submitted values as null by adding the following context paramter to the web.xml:

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

This way the @NotNull will be triggered for empty fields.

Upvotes: 3

Related Questions