Matt Handy
Matt Handy

Reputation: 30025

Validating empty fields with inline validation method and validator class

I have the following input field:

<h:inputText value=".." validator="#{labController.validateValue}"/>

If the field is empty it will not be validated (validateValue in labController is not called).

But using a separate validator class:

<h:inputText value=".." >
  <f:validator validatorId="labDateValidator"/>
</h:inputText>

then its validate method well be called even with an empty input field?

This is what I observe. Is this behavior dependent on implementation or version (I am using Mojarra 2.1) ?

Background is that I want to use my own method/class for all validation tasks including required validation. Does it work with validator class only?

Upvotes: 4

Views: 2383

Answers (1)

BalusC
BalusC

Reputation: 1109875

You've hit an oversight in JSF. The validator is wrapped in a MethodExpressionValidator which according to the source of its validate() method indeed skips validation when the value is null.

if (value != null) {
    try {
        ELContext elContext = context.getELContext();
        methodExpression.invoke(elContext, new Object[]{context, component, value});
        ...

This is not considering the new JSF 2.0 javax.faces.VALIDATE_EMPTY_FIELDS context parameter which defaults to true. It should actually be doing the same as UIInput#validate().

if (!isEmpty(newValue) || validateEmptyFields(context)) {
    try {
        ELContext elContext = context.getELContext();
        methodExpression.invoke(elContext, new Object[]{context, component, value});
        ...

This has already been reported as Mojarra issue 1508. I've voted it and added a new comment to wake them up.

Upvotes: 6

Related Questions