【问题标题】:Custom error message in @Digits annotation@Digits 注释中的自定义错误消息
【发布时间】:2020-04-03 09:19:18
【问题描述】:

我正在尝试在 Hibernate 验证 API 的帮助下验证 BigDecimal 字段 - 使用 @Digits 注释

@Digits(integer = 12, fraction = 2, 
        message = "numeric value out of bounds (min 0.01, max 999999999999.99)")
private BigDecimal amount = null;

当我传递金额值 123.123 时,我收到的错误消息是

'Classname.amount' 数值超出范围(最小值 0.01,最大值 999999999999.99)

但问题不是无效范围,而是格式。我们只允许 2 个小数。
我想要两条消息,一条用于无效范围,第二条用于无效分数。

是否可以有两条不同的消息?

我尝试使用消息表达式进行插值,但它的选项有点有限

【问题讨论】:

    标签: java annotations message digits


    【解决方案1】:

    你可以试试

    @DecimalMin( value = "0.01", message ="too small")
    @DecimalMax( value = "99999999999", message ="too big")
    @Digits( integer=12, fraction=2, message = "bad format")
    private BigDecimal amount = null;
    

    【讨论】:

      【解决方案2】:
      @NotNull
      @Positive
      @Digits(integer = 12, fraction = 2, message = "${validatedValue > 999999999999.99 ? "
                  + "'numeric value out of bounds (min 0.01, max 999999999999.99)':"
                  + "'value cannot contain more than two fractional digits.'}")
          private BigDecimal amount;
      

      我能够使用带有消息表达式的插值解决问题

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-08-11
        • 1970-01-01
        • 1970-01-01
        • 2018-08-12
        • 2014-12-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多