1

I am trying to add message to the javax.validation annotations in my Spring Boot app as shown below:

public static final String CANNOT_EMPTY = "%s field cannot be empty";


@Value
public class CreatePostRequest {

    @NotBlank(message = String.format(CANNOT_EMPTY, title))
    private String title;

    // other fields
}

I am getting "Attribute value must be constant" error for the format() method. So, how should I properly set messages for the javax.validation annotations in my API requests? I do not want to add text to all of the fields and instead try to manage them in a Constant class and add the constant text variables to that annotations (for now, no need internationalization).

So, is there a better way? Any help would be appreciated.

Jack
  • 1
  • 21
  • 118
  • 236

1 Answers1

1

The better way is to handle it in a RestControllerAdvice, where you can easily append a property name to a message. For example, you can define a RestControllerAdvice as shown below:

@RestControllerAdvice
public class GlobalExceptionHandler {

  @ExceptionHandler(MethodArgumentNotValidException.class)
  public ResponseEntity<List<String>> handleValidationErrors(MethodArgumentNotValidException ex) {
    List<String> errors =
        ex.getBindingResult().getFieldErrors().stream()
            .map(i -> i.getField() + " " + i.getDefaultMessage())
            .collect(Collectors.toList());
    return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);
  }
}

The response for the field marked as @NotBlank would be ["title must not be blank"], and if you want to add a custom message @NotBlank(message="field cannot be empty") the response would be ["title field cannot be empty"].

Toni
  • 3,296
  • 2
  • 13
  • 34
  • Thanks a lot, it sounds good. Bot I am looking a more professional way that is dedicated to this purpose like `MessageSource`. As far as I see after some search, it also support intrenationalization. I use @ControllerAdvice and Global Exception handler in my project, but this time I am looking for a specific and more elegant solution for this issue. – Jack Feb 25 '23 at 14:59
  • By the way, I cannot vote up as I have not enough repo. Would you consider any vote up pls? – Jack Feb 25 '23 at 15:00
  • And do you have any idea about MessageSource? Would you suggest to use it for this scenario? – Jack Feb 25 '23 at 15:01
  • Check [bernie's answer](https://stackoverflow.com/a/36344999/10231374), it should be useful if you want localized messages and field names. – Toni Feb 25 '23 at 16:48
  • Thanks a lot, but MessageSource seems to be clearer than that approach. Nevertheless, I opened a new question about that. Could you have a look at that? >>> https://stackoverflow.com/questions/75568330/custom-validation-message-in-spring-boot-with-internationalization – Jack Feb 25 '23 at 20:48