【问题标题】:Replace default message for Constraint Validator替换约束验证器的默认消息
【发布时间】:2019-01-23 10:44:19
【问题描述】:

我正在尝试更改 Spring 中约束验证器的默认消息。

我尝试根据这样的验证错误添加新消息:

context.buildConstraintViolationWithTemplate("My custom message").addConstraintViolation();

适用于每种情况。

@Override
public boolean isValid(MyData data, ConstraintValidatorContext ctx) {
    boolean valid = false;
    if (!StringUtils.isEmpty(data.getDocumentType())) {
        if (data.getDocumentType().equalsIgnoreCase("N")) {
            valid = isValidTypeN(data.getDocument());
            if(!valid) context.buildConstraintViolationWithTemplate("My custom message for type N").addConstraintViolation();
        } else if(data.getDocumentType.equalsIgnoreCase("R")){
            valid = isValidTypeR(data.getDocument());
            if(!valid) context.buildConstraintViolationWithTemplate("My custom message for type R").addConstraintViolation();
        } else if(data.getDocumentType.equalsIgnoreCase("P")) {
            valid = isValidTypeP(data.getDocument());
            if(!valid) context.buildConstraintViolationWithTemplate("My custom message for type P").addConstraintViolation();
        }
    }       
    return valid;
}

但这是添加一条新消息,而不是替换约束中的默认消息,因此当我在表单页面中显示错误时,它会同时显示默认消息和我添加的消息,而不仅仅是我动态添加的消息。

【问题讨论】:

  • 你在注释中设置了什么默认值?
  • 只是一条默认消息String message() default "whatever this is a default message"
  • 所以,您可以更改它,也可以通过将值传递给注释来更改它
  • 显然。但我的问题是关于根据错误类型动态更改该值?

标签: java spring


【解决方案1】:

这段代码应该可以完成这项工作:

context.disableDefaultConstraintViolation()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-30
    • 1970-01-01
    • 2020-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多