Unable to set validation error message using SpringBoot@DateTimeFormat

Asked 2 years ago, Updated 2 years ago, 356 views

I would like to validate the Date type in ExampleForm.java using @DateTimeFormat in the Spring Boot application, but when I use typeMismatch in messages.properties, the message definition is not set in the message.
I looked into various things, but I didn't know how to do it.

Please tell me the solution.

ExampleForm.java

@Getter
@Setter
public classExampleForm{
  @NotNull(message="searchName is Empty!!")
  private String searchName;

  // I want to set validation messages for this field
  @DateTimeFormat(pattern="yyyyMMddhhmmss")
  private Date searchDate;
}

ExampleController.java

@RestController
public classExampleForm{

  @GetMapping("/example/search")
  publicList<String>searchExample(@ValidatedExampleForm)throwsException{

    // ...handling...

    return list;
  }

}

ExceptionControllerAdvice.java

@RestControllerAdvice
public classExceptionControllerAdvice{

  @ExceptionHandler (BindException.class)
  publicList<String>handleExampleBindException(BindException bindEx)throwsException{
    List<String>list=new ArrayList<String>();;
    for(FieldError: bindEx.getBindingResult().getFieldErrors()){
      list.add(err.getDefaultMessage());
    }
    return list;
  }

}

MessageConfig.java

@Configuration
public class MessageConfig {

  @ Bean
  public MessageSource messageSource(){
    ReloadResourceBundleMessageSourcems= ReloadResourceBundleMessageSource();
    ms.setBeanname("classpath:messages");
    ms.setDefaultEncoding("UTF-8");
    return ms;
  }

  @ Bean
  public MessageSourceAccessor messageSourceAccessor(){
    LocalValidatorFactoryBean lvfb = LocalValidatorFactoryBean();
    lvfb.setValidationMessageSource(messageSource());
  }

}

messages.properties

typeMismatch.java.util.Date=Invalid Date Format.
typeMismatch.exampleForm.searchDate=searchDate of exampleForm is InvalidDateFormat.
typeMismatch.searchDate=searchDate is Invalid Date Format.

Operation verification command

 curl-X GET "http://localhost:port/example/search?searchName=xxxxxxxx&searchDate=xxxxxxxxxxxxxx"

Supplemental
The default message included the following:

Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property' searchDate'; nested exception is java.lang.IllegalArgumentException: could not parse date: Unparseable date: "xxxxxxx"

java spring spring-boot rest

2022-09-30 21:56

1 Answers

You must retrieve the corresponding message from MessageSource.
Messages retrieved in getDefaultMessage() are only "default" messages.

@RestControllerAdvice
@RequiredArgsConstructor
public classExceptionControllerAdvice{

    private final MessageSource;

    @ExceptionHandler (BindException.class)
    publicList<String>handleExampleBindException(finalBindException bindEx)throwsException{
        final List<String>list=new ArrayList<>();
        for(final FieldError: bindEx.getBindingResult().getFieldError()){
            list.add(messageSource.getMessage(err, LocaleContextHolder.getLocale()));
        }
        return list;
    }

}

If Bean Validation (Hibernate Validation) fails, the message defined in ValidationMessages.properties (*) becomes the default message, so you can get the message you expected in getDefaultMessage().

However, this error is not validation using Bean Validation, but binding.

デフォルト Default setting: LocalValidatorFactoryBean customized to messages.properties

in the questionnaire code.

Note:

Since DefaultBindingErrorProcessor setting the default error message for the question, replacing this class (pre-setting the desired string in the default message) may be another solution.

p>


2022-09-30 21:56

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.