Using I18n messages while validating forms with JSR-303

一笑奈何 提交于 2019-12-11 23:25:50

问题


My app is fully-configured spring-boot app with thymeleaf templates engine. I18n configured as well so I can use it within my templates. Here is the config I use:

spring.messages.basename=i18n/messages

While manual validating fields I18n also work fine:

BindingResult result;
result.rejectValue("field", "some.i18n.code");

But once I want to implement some custom ConstraintValidator objects and use message field - no I18n involved, I receive plain codes as a response instead of a message. I.e.

{some.i18n.code}

I tried this solution - no result. This on as well - same result.

What am I missing?


回答1:


I guess I found the solution, maybe it will be helpful to others. All you have to do is to add the following definitions into your WebMvcConfigurerAdapter configuration implementation:

@Autowired
private MessageSource messageSource;

@Bean
public LocalValidatorFactoryBean validator() {
     LocalValidatorFactoryBean validatorFactoryBean = new LocalValidatorFactoryBean();
     validatorFactoryBean.setValidationMessageSource(messageSource);

     return validatorFactoryBean;
}

@Override
public Validator getValidator() {
     return validator();
}



回答2:


An alternative solution is just declare this bean in any of your @Configuration classes:

@Bean
public LocalValidatorFactoryBean localValidatorFactoryBean(MessageSource messageSource) {
    LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
    bean.setValidationMessageSource(messageSource);
    return bean;
}

Due to declaring this, now my custom error codes from my custom validators are being searched for in my messages.properties (that I also have in a i18n subdirectory by declaring spring.messages.basename=i18n/messages).

Example validator code:

public class ContestValidator implements ConstraintValidator<ValidContest, CreateContestParameters> {

  @Override
  public void initialize(ValidContest constraintAnnotation) {

  }

  @Override
  public boolean isValid(CreateContestParameters contestParameters, ConstraintValidatorContext context) {
    boolean result = true;

    if (!endDateIsEqualOrAfterStartDate(contestParameters)) {
        context.buildConstraintViolationWithTemplate("{Contest.endDate.invalid}")
               .addPropertyNode("endDate").addConstraintViolation();
        result = false;
    }
    if (!registrationDeadlineIsBeforeStartDate(contestParameters)) {
        context.buildConstraintViolationWithTemplate("{Contest.registrationDeadline.invalid}")
               .addPropertyNode("registrationDeadline").addConstraintViolation();
    }
    return result;
  }
}


来源:https://stackoverflow.com/questions/34878877/using-i18n-messages-while-validating-forms-with-jsr-303

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!