首页 > 解决方案 > 如何在验证器的消息中写入 java 变量值

问题描述

对于 OTP 长度,我使用 6,我从变量中获取

static final int OTP_LENGTH = 6;

@Size(min = OTP_LENGTH, max = OTP_LENGTH, message = "OTP Length should be {OTP_LENGTH} !!")
private String otp;

如果大小不是 OTP_LENGTH,我会收到错误消息。

"fieldErrors": [
    {
      "field": "password",
      "message": "Not a Base64 string !!"
    },
    {
      "field": "otp",
      "message": "OTP Length should be {OTP_LENGTH} !!"
    }
  ]

我也试过

@Size(min = OTP_LENGTH, max = OTP_LENGTH, message = "OTP Length should be ${OTP_LENGTH} !!")
private String otp;

但是,OTP_LENGTH 6 没有设置。

期望:-“OTP 长度应该是 6 !!”

而且,是否有任何其他验证器只需要 1 个长度。

@Size,@Length 可以取最大值,@Size(max = OTP_LENGTH),但 min 将再次为 0。如果我不覆盖消息,它将显示长度应在 0 和 6 之间。

标签: javahibernate-validator

解决方案


您必须使用@Size 注释中的min和字段,例如:max

@Size(min = OTP_LENGTH, max = OTP_LENGTH, message = "OTP Length must be between {min} and {max}")
private String otp;

对于价值,你可以validatedValue财产。


推荐阅读