简体   繁体   中英

How to receive validation message on frontend in Spring Framework?

I have validation constraints:

 @Size(min = 3, message = "First name '${validatedValue} must be minimum 3 characters long'")
    @Pattern(regexp = "^A(\\w)+$", message = "First name must start with capital letter")
    private String firstName;

In controller I have @Valid annotation for the request body argument. If validation is failed - Spring resolves this, but I do not receive message . Why does it happen?

I have tried to add this handler:

    @ExceptionHandler(ConstraintViolationException.class)
    public ResponseEntity<String> handle(ConstraintViolationException constraintViolationException) {
        Set<ConstraintViolation<?>> violations = constraintViolationException.getConstraintViolations();
        String errorMessage = "";
        if (!violations.isEmpty()) {
           ...
        } else {
            errorMessage = "ConstraintViolationException occured.";
        }

        return new ResponseEntity<>(errorMessage, HttpStatus.BAD_REQUEST);
    }

I guess, It is possible by getting field error.

Hope below sample works out

@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ResponseBuilder> handleMethodArgumentNotValidException(HttpServletRequest request,
            MethodArgumentNotValidException ex) {

    BindingResult result = ex.getBindingResult();
    List<org.springframework.validation.FieldError> fieldErrors = result.getFieldErrors();
    String errorMessage = messageSource.getMessage(ApiResponseCode.ERR_COMMON_REQ_BODY.getCode(),
                new Object[] {
                        fieldErrors.stream().map(field -> field.getDefaultMessage()).collect(Collectors.joining(",")) },
                Locale.US);
    LOGGER.error(errorMessage, ex);
    return new ResponseEntity<ResponseBuilder>(
                new ResponseBuilder.Builder(ApiResponseCode.ERR_COMMON_REQ_BODY.getCode(), errorMessage).build(),
                HttpStatus.OK);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM