访问Hibernate Validator消息

时间:2017-05-04 10:57:02

标签: spring spring-boot hibernate-validator spring-validator

我正在使用带有Spring Boot的Hibernate Validator。我在类中有一个变量,我在下面注释。

Public class User {

@Pattern(regexp=".+@.+\\..+", message="Wrong email!")
private String userEmail;

}

我在控制器中使用验证。

@PostMapping("/users")
public ResponseEntity addUser(@Valid @RequestBody User user, BindingResult result) {

    if(result.hasErrors()) {
        log.info("There are errors in the input");
    }

    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();
        Set<ConstraintViolation<User>> inputErrors = validator.validate(user);

        log.info("Errors: "  + inputErrors.toString());
}

是否更容易通过工厂访问验证消息?像

这样的东西
result.getMessage();

1 个答案:

答案 0 :(得分:0)

您可以将消息源自动装配到控制器

@Autowired
private MessageSource messageSource;

并获取消息

messageSource.getMessage(<your key from the error>, null, locale);

您使用区域设置来获取正确的本地化文本。您需要迭代错误以获取所有发现的验证错误的所有消息。

相关问题