jsfbean-validationjsf-2.2viewparams

@NotNull Bean Validation ignored for viewParam


Problem

I'm trying to validate a mandatory GET request parameter.

In the view I've added a corresponding viewParam tag.

<f:metadata>
    <f:viewParam name="customerId" value="#{customerDetailBean.customerId}"/>
</f:metadata>

And my CDI bean looks like this

@Model
public class CustomerDetailBean {

    @NotNull
    private Integer customerId;

    public Integer getCustomerId() {
        return customerId;
    }

    public void setCustomerId(Integer customerId) {
        this.customerId = customerId;
    }
}

When I use the following request, validation works fine and the expected validation message is displayed.

http://localhost:8080/getsupport/customerdetail.jsf?customerId=

However, when I change the request by removing the parameter customerId, validation is skipped and no message is shown.

http://localhost:8080/getsupport/customerdetail.jsf

Is there a way to make it work as expected?

Workaround

I've changed my viewParam declaration to

<f:metadata>
    <f:viewParam name="customerId" value="#{customerDetailBean.customerId}" required="true" />
</f:metadata>

That updated version works fine with the second request. Anyway I would prefer to use bean validation.

My setup

web.xml

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

Solution

  • This is, unfortunately, "working as designed". All validation is skipped when nothing's been submitted. Only the <f:viewParam required> has special treatment. It's also considered when nothing's been submitted. See also UIViewParameter#processValidators() javadoc and source code.

    In the Mojarra issue tracker I can only find issue 3058 as a related issue, whereby the <f:validateRequired> isn't being considered. This is technically actually exactly the same problem as you're facing with @NotNull. I've created issue 3339 on this.

    In the meanwhile, your best bet is falling back to required="true". A custom component can also, but as far as I see this isn't going to be trivial.


    Update: after all, the fix is relatively easy and has been implemented in OmniFaces <o:viewParam> in the current 2.0 snapshot release.