使用内联验证方法和验证器类验证空字段

使用内联验证方法和验证器类验证空字段

本文介绍了使用内联验证方法和验证器类验证空字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下输入字段:

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

如果该字段为空,则不会被验证(不会调用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>

那么即使输入字段为空,它的validate方法也能被调用吗?

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

这就是我观察到的.这种行为取决于实现或版本(我正在使用Mojarra 2.1)吗?

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?

推荐答案

您在JSF中遇到了一个疏漏. validator包装在 MethodExpressionValidator 中,根据其方法确实会跳过验证.

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});
        ...

这没有考虑默认为true的新JSF 2.0 javax.faces.VALIDATE_EMPTY_FIELDS上下文参数.它实际上应该与.

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});
        ...

这已经被报道为 Mojarra版本1508 .我已对其投票,并添加了新评论以唤醒他们.

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

这篇关于使用内联验证方法和验证器类验证空字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 23:37