DevZer0
DevZer0

Reputation: 13535

define messages based on locale in hibernate validations

I am trying to use validation error messages to be based on the current active locale as follows

@Entity
@Table(name = "footable")
public class TestModel extends BaseEntity {
   @NotEmpty(message = "${notEmpty}")
   private String name;
}

However it doesn't seem to be able to resolve properties, I get

EL expression '${notEmpty}' references an unknown property

I have notEmpty defined in both messages.properties and application.properties

I also tried using @Value from lombok that results in a compile time error rather than a runtime error as well.

Upvotes: 1

Views: 110

Answers (2)

Ken Bekov
Ken Bekov

Reputation: 14015

Add to your config

@Bean
public ReloadableResourceBundleMessageSource messageSource() {
    ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
    messageSource.setBasename("classpath:messages");
    messageSource.setDefaultEncoding("UTF-8");
    return messageSource;
}

@Bean
public LocalValidatorFactoryBean validatorFactoryBean() {
    LocalValidatorFactoryBean validatorFactoryBean = new LocalValidatorFactoryBean();
    validatorFactoryBean.setValidationMessageSource(messageSource());
    validatorFactoryBean.setApplicationContext(context);
    return validatorFactoryBean;
}

Remove message from annotation

public class TestModel extends BaseEntity {
    @NotEmpty
    private String name;
}

To the messages.properties add message as

NotEmpty.testModel.name=The message of error

The name NotEmpty.testModel.name follows the naming convention.

Upvotes: 1

adn.911
adn.911

Reputation: 1314

No need for the $, use message = "{notEmpty}" instead .

Upvotes: 0

Related Questions