如何按顺序检查多个 Spring DTO 验证?
How to check multiple Spring DTO validation by sequence?
我已请求 DTO 使用 spring 验证如下。
@Getter
@Setter
public class DeviceData implements Serializable {
@NotBlank(message = "device id required")
private String deviceId;
@NotBlank(message = "client trans id required")
@Pattern(regexp = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"
, message = "client trans id format error")
private String clientTransId;
@NotBlank(message = "device info required")
private String deviceInfo;
}
我希望 @NotBlank
先检查,当它为 false 时,不检查 @Pattern
。当它为真时检查 @Pattern
。
它是怎么做到的?请帮帮我。谢谢
您可以使用Group
,如下代码所示:
首先,您需要声明一个新组:
public interface Group1 {
}
其次,根据需要声明自定义序列:
// Default is nessary here
@GroupSequence({Default.class, Group1.class})
public interface Sequence {
}
然后,在您的 DTO 字段中添加组:
@NotBlank(message = "client trans id required", groups = {Default.class})
@Pattern(regexp = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$", message = "client trans id format error", groups = {Group1.class})
private String clientTransId;
最后,使用验证器和您的 Sequence
接口进行验证:
DeviceData test = new DeviceData();
test.clientTransId = "";
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Set<ConstraintViolation<DeviceData>> set = validator.validate(test, Sequence.class);
我已请求 DTO 使用 spring 验证如下。
@Getter
@Setter
public class DeviceData implements Serializable {
@NotBlank(message = "device id required")
private String deviceId;
@NotBlank(message = "client trans id required")
@Pattern(regexp = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"
, message = "client trans id format error")
private String clientTransId;
@NotBlank(message = "device info required")
private String deviceInfo;
}
我希望 @NotBlank
先检查,当它为 false 时,不检查 @Pattern
。当它为真时检查 @Pattern
。
它是怎么做到的?请帮帮我。谢谢
您可以使用Group
,如下代码所示:
首先,您需要声明一个新组:
public interface Group1 {
}
其次,根据需要声明自定义序列:
// Default is nessary here
@GroupSequence({Default.class, Group1.class})
public interface Sequence {
}
然后,在您的 DTO 字段中添加组:
@NotBlank(message = "client trans id required", groups = {Default.class})
@Pattern(regexp = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$", message = "client trans id format error", groups = {Group1.class})
private String clientTransId;
最后,使用验证器和您的 Sequence
接口进行验证:
DeviceData test = new DeviceData();
test.clientTransId = "";
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Set<ConstraintViolation<DeviceData>> set = validator.validate(test, Sequence.class);