I have a class PojoB
which contains a field code and a field of class PojoA
:
@Data
public class PojoB {
@Size(min = 1, max = 5)
@NotBlank()
@Pattern(regexp = "[0-9]+")
private String code;
@Valid
private PojoA pojoA;
}
@Data
public class PojoA {
@Size(min = 1, max = 5)
@NotBlank()
@Pattern(regexp = "[0-9]+")
private String code;
}
And PojoB
is used as a request body of /testSpringValidation1
, validations are enabled.
Now regarding the new API /testSpringValidation2
, the pojoA.code can allow more characteres and no change/difference on other validation rules comparing /testSpringValidation1. So @Pattern(regexp = "[0-9a-z]+", groups = LessValidation.class)
is added. But how can I implement it without changing exisitng code?
public interface LessValidation extends Default {
}
@PostMapping("/testSpringValidation2")
public PojoB testSpringValidation2(@RequestBody @Validated({LessValidation.class}) PojoB reqBody) {
return reqBody;
}
@Data
public class PojoA {
@Size(min = 1, max = 5)
@NotBlank()
@Pattern(regexp = "[0-9]+")
@Pattern(regexp = "[0-9a-z]+", groups = LessValidation.class)
private String code;
}
When triggering /testSpringValidation2
API by this reqbody,
{
"code":"12345",
"pojoA":{
"code": "12ab"
}
}
I received this error
error:
{
"type": "error",
"code": "400",
"details": "mandatory parameter pojoA.code is invalid: must match "[0-9]+""
}
But if I don’t make LessValidation extend Default, then other validation rules (like validations on pojoB.code
) will also be skipped.
Thanks!
2