Spring custom validation message

Spring custom validation message

The following few step is all you need to create custom validation message.

Example form component

Important to enclose your message within { }, Message without enclose {} will directly print as message

message = “{error.merchant.code}” – refer to property value

message = “error.merchant.code” – directly display as error.merchant.code

@Component
public class PaymentForm {

    @NotBlank(message="{error.merchant.code}")
    private String merchant_code;
        
    // code omitted
}

Web configuration file.

setBasename() method always include with classpath. If your properties is put under /src/main/resources/

messageSource.setBasename(“message”);   wrong

messageSource.setBasename(“classpath:message”);   correct

// code omitted
@Bean(name = "messageSource")
public MessageSource messageSource() {
   ReloadableResourceBundleMessageSource messageSource = 
       new ReloadableResourceBundleMessageSource();
   messageSource.setBasename("classpath:messages");
   messageSource.setCacheSeconds(5);
   return messageSource;
}

@Override
public Validator getValidator() {
  LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
  validator.setValidationMessageSource(messageSource());
  return validator;
}

 

messages.property

error.merchant.code= Merchant code error

 

Alternative solution

The alternative solution by overwrite the default value. Create a file called ValidationMessages.properties under /src/main/resources/ and add your custom message.

ValidationMessages.properties

error.merchant.code= Merchant code error

This solution does not require you to override the default method getValidator().

// code omitted
@Bean(name = "messageSource")
public MessageSource messageSource() {
   ReloadableResourceBundleMessageSource messageSource = 
       new ReloadableResourceBundleMessageSource();
   messageSource.setBasename("classpath:messages");
   messageSource.setCacheSeconds(5);
   return messageSource;
}

@Override
public Validator getValidator() {
  LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
  validator.setValidationMessageSource(messageSource());
  return validator;
}

 

Write a Reply or Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.