我希望 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 类中,这是否可能?
@Length(min = 6, max = 20, applyIf = "username is not blank")