Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...