如何使 DTO 接受空字符串字段,但如果它们不为空则应用 JPA 验证?

问题描述 投票:0回答:1

我希望 DTO 使用验证器注释来验证字段输入,但前提是相关字段不是请求中的空字符串。

例如,我有一个 UserDto,它接受一个长度必须在 6 到 20 之间的字符串用户名字段。但我也希望请求能够为此字段发送一个空字符串。

请求示例:

{
  "username": "", // empty field won't be validated
  "email": "[email protected]",
  "password": "password123",
  etc...
}

示例实体:

@Data
public class AdminUpdateUserDto {
    @Nullable
    @Length(min = 6, max = 20) // applies only if string isn't empty
    private String username;

    @Email
    @Length(min = 5, max = 30)
    private String email;

    @Length(min = 6, max = 20)
    private String password;

如果不创建自定义验证器,或者更好地说,在 Dto 类中,这是否可能?

java hibernate jpa
1个回答
0
投票
@Length(min = 6, max = 20, applyIf = "username is not blank")

jug.bg/springboot-validation

© www.soinside.com 2019 - 2024. All rights reserved.