Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

jsf 2 - 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?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...