0

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.

Jack
  • 1
  • 21
  • 118
  • 236

1 Answers1

1

You can define properties in messages.properties for the validation errors. With Spring Boot, there is no need to register a MessageSource bean; it is done automatically and additional configuration can be done via application.properties.

name.size-error=min {min}, max {max} character length
name.not-blank=name cannot be empty
email.error=email is not valid

Then, you can use those properties for the validation message in each annotation.

@Size(min = 3, max = 50, message = "{name.size-error}")
@NotBlank(message = "{name.not-blank}")
private String name;

@Email(message = "{email.error}")
private String email;
Unmitigated
  • 76,500
  • 11
  • 62
  • 80