使用BindingResult:Spring从表单验证字段

时间:2018-02-19 14:44:12

标签: java spring hibernate

如何使用Spring中的BindingResult在表单输入中验证整数类型值?

当我尝试验证输入时,我得到了一个例外。我经历了很多帖子但完全不理解这个概念。

这里的问题不是验证,而是数据绑定。数据绑定在验证之前发生,并且只有在所有字段都已正确转换和绑定时才会调用验证。在我的情况下,绑定步骤失败。如果我在这里错了,请纠正我。

<div class="form-group">
    <div class="col-sm-9">
        <label  th:if="${#fields.hasErrors('age')}" th:errors="age"
                    class="validation-message"></label>
            <input type="number" th:field="*{age}"
            placeholder="Age" class="form-control" /> 
    </div>
</div>

映射请求的代码

@RequestMapping(value = "/registration", method = RequestMethod.POST)
public ModelAndView createNewUser(@Valid User user, BindingResult bindingResult) {
    ModelAndView modelAndView = new ModelAndView();
    User userExists = userService.findUserByEmail(user.getEmail());
    if (userExists != null) {
        bindingResult
                .rejectValue("email", "error.user",
                        "There is already a user registered with the email provided");
    }
    if (bindingResult.hasErrors()) {
        modelAndView.setViewName("registration");
    } else {
        userService.saveUser(user);
        modelAndView.addObject("successMessage", "User has been registered succssfully");
        modelAndView.addObject("user", new User());
        modelAndView.setViewName("registration");
        }
    return modelAndView;
}

User.class

@Column(name = "age")
@NotEmpty(message = "*age is mandatory")
private Integer age;

例外:

javax.validation.UnexpectedTypeException: HV000030: No validator could be found for constraint 'javax.validation.constraints.Size' validating type 'java.lang.Integer'. Check configuration for 'age'
    at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.throwExceptionForNullValidator(ConstraintTree.java:229) ~[hibernate-validator-5.2.4.Final.jar:5.2.4.Final]
    at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.getConstraintValidatorNoUnwrapping(ConstraintTree.java:310) ~[hibernate-validator-5.2.4.Final.jar:5.2.4.Final]
    at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.getConstraintValidatorInstanceForAutomaticUnwrapping(ConstraintTree.java:244) ~[hibernate-validator-5.2.4.Final.jar:5.2.4.Final]

1 个答案:

答案 0 :(得分:1)

非空约束用于字符串和集合。 https://docs.jboss.org/hibernate/beanvalidation/spec/2.0/api/javax/validation/constraints/NotEmpty.html

要验证Integer是否有某个值,应使用@NotNull约束。