【问题标题】:Format message in custom JSF validator在自定义 JSF 验证器中格式化消息
【发布时间】:2024-12-05 09:50:02
【问题描述】:

我正在实现一个自定义验证器。存储在资源中的消息的详细信息。以下是消息示例:Value is required for {0}。 {0} 应包含组件的标签。

@FacesValidator("customValidator")
public class CustomValidator implements Validator {

    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
    if (validatorCondition()) {
            String summary = Res.getString("error");
            String detail =  ... format detail here
            throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, summary, detail));
        } 
    }
}

如何格式化验证方法中显示的消息?

【问题讨论】:

    标签: java validation jsf jsf-2 custom-component


    【解决方案1】:

    使用MessageFormat#format()

    String template = "Value is required for {0}.";
    String label = component.getAttributes().get("label"); // Don't forget to handle nulls. JSF defaults to client ID.
    String message = MessageFormat.format(template, label);
    // ...
    

    【讨论】:

      最近更新 更多