I am creating Spring boot APIs and one of the API consumening data below:
class DataRequest{
@Size(min=1, max=10)
private String dataTitle;
private List<String> emails;
}
How can we validate List like all strings must be valid emails or matching with some pattern by utilizing a validation framework in Spring controller using @Valid
annotation?
Bean validation allows you to put the validating annotation inside the container type such as List
. They refer this as the container element constraint validation.
So you can do something likes :
class DataRequest{
@Size(min=1, max=10)
private String dataTitle;
private List<@Email String> emails;
}
or
class DataRequest{
@Size(min=1, max=10)
private String dataTitle;
private List<@Pattern(regexp = "[A-Za-z\\d]*") String> emails;
}