0

我有以下问题。我只提供 PIN 时使用表格。我有验证器检查它是否是 4 位数字。然后将提交的操作设置为检查 PIN 是否存在于数据库中的方法。如果不是,则 message = "no PIN"; 我在表单下方的输出标签中使用了消息。以前它是空的,所以那里没有消息。现在它变为“无 PIN”,但我必须在再次单击提交按钮后将其清除,因为当您输入例如“12as”PIN 并且验证器会处理它时,错误消息不会消失。我应该如何实施这种情况?也许在这种情况下使用输出标签是一个错误的想法?

4

2 回答 2

4

您不应该在操作方法中执行验证。您应该使用真正的验证器。

只需Validator相应地实现接口即可。例如

@FacesValidator("pinValidator")
public class PinValidator implements Validator {

    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        String pin = (String) value;

        if (pin == null || pin.isEmpty()) {
            return; // Let required="true" deal with it if necessary.
        }

        if (!pin.matches("\\d{4}")) {
            throw new ValidatorException(new FacesMessage("PIN must be 4 digits"));
        }

        if (!somePinService.exists(pin)) {
            throw new ValidatorException(new FacesMessage("PIN is unknown"));
        }    
    }

}

按如下方式使用它:

<h:outputLabel for="pin" value="PIN" />
<h:inputText id="pin" value="#{bean.pin}" validator="pinValidator" />
<h:message for="pin" />

验证器异常的 faces 消息将最终<h:message>与触发验证器的组件关联。

如果您使用 ajax 提交表单,请不要忘记确保在 ajax 渲染时也考虑到该消息。


与具体问题无关,JSF<h:outputLabel>生成一个 HTML<label>元素,用于标记表单元素(例如<input><select>等)。它绝对不打算显示任意文本,例如验证消息。我建议暂时把 JSF 放在一边,开始学习基本的 HTML。这样,您将更好地了解选择哪些 JSF 组件来获得所需的 HTML 输出。

于 2013-05-10T22:43:32.257 回答
-1

您可以在验证器之外使用 JSF 消息组件:对于您在表单中输入的消息:

 <h:message for="PIN"/> 

在您的托管 bean 中,您可以使用以下方法添加 FacesMessage:

FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_WARN,"No pin summary message","No pin detail message");
FacesContext.getCurrentInstance().addMessage("PIN", message);

此处无需使用 outputLabel。

于 2013-05-10T22:11:15.860 回答