I am trying to apply a proper approach for my validation annotations as shown below:
public class UserRequest {
@Size(min = 3, max = 50)
@NotBlank(message = "name cannot be empty and min 3, max 50 character length")
private String name;
@Email(message = "email is not valid")
private String email;
}
I need the following features:
1. As shown for the name
field, I need to get field name, and min-max parameter values in the validation message.
2. I should be able to localize these messages in the future when I need.
So, how should I implement such kind of approach in Spring Boot apps? Is MessageSource
usage mentioned on Custom Validation MessageSource in Spring Boot a proper approach for this?
Update: When I try the approach below, I get the following response:
{
"timestamp": "26.02.2023 01:10:15",
"status": 400,
"error": "Bad Request",
"exception": "org.springframework.web.bind.MethodArgumentNotValidException",
"message": "Validation failed for object='createPostRequest'. Error count: 1",
"errors": [
{
"codes": [
"NotBlank.createPostRequest.name",
"NotBlank.name",
"NotBlank.java.lang.String",
"NotBlank"
],
"arguments": [
{
"codes": [
"createPostRequest.name",
"name"
],
"arguments": null,
"defaultMessage": "name",
"code": "name"
}
],
"defaultMessage": "{name.not-blank}",
"objectName": "createPostRequest",
"field": "name",
"rejectedValue": null,
"bindingFailure": false,
"code": "NotBlank"
}
],
"path": "/api/v1/posts"
}
So, it does not seem to convert messages provided by message.properties
in the resources folder.