How to show MethodArgumentNotValidException message according to Projo field in spring boot?

I am using spring boot spring-boot-starter-validation to check the empty field. But I need to validate the message account to my projo file. Here is my projo file:

        public class TestRequest {

        @NotBlank(message = "Name is required")
        @NotEmpty(message = "Name is required")
        private String name ;

        @NotBlank(message = "Email is required")
        @NotEmpty(message = "Email is required")
        private String email ;

        @NotBlank(message = "Phone is required")
        @NotEmpty(message = "Phone is required")
        private String phone ;
    }

But when I call it shows below error:

{
"phone": "Phone is required",
"name": "Name is required",
"email": "Email is required"
 }

I want to show message according to my projo class properties like below:

    {
      "name": "Name is required",
      "email": "Email is required",
      "phone": "Phone is required",
      }

That means according to my projo name validation message will come first, then email & then phone.

Here is my ControllerAdvice methos

         @ExceptionHandler(MethodArgumentNotValidException.class)
        public ResponseEntity<Object> handleValidationExceptions(MethodArgumentNotValidException ex) {
            Map<String, String> errors = new HashMap<>();
            ex.getBindingResult().getAllErrors().forEach(error -> {
                String fieldName = ((FieldError) error).getField();
                String errorMessage = error.getDefaultMessage();
                errors.put(fieldName, errorMessage);
            });
            return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);
        }

How to show validation message according to my project?

  • A json object is unordered.

    – 

Leave a Comment