gpt4 book ai didi

java - 使用 BindingResult 验证表单中的字段 :Spring

转载 作者:行者123 更新时间:2023-12-02 11:36:59 26 4
gpt4 key购买 nike

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

当我尝试验证输入时,出现异常。我已经阅读了很多帖子,但没有完全理解这个概念。

这里的问题不在于验证,而在于数据绑定(bind)。数据绑定(bind)发生在验证之前,并且仅当所有字段都已正确转换和绑定(bind)时才会调用验证。就我而言,绑定(bind)步骤失败。如果我错了,请纠正我。

<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;
}

用户.类

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

异常(exception):

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]

最佳答案

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

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

关于java - 使用 BindingResult 验证表单中的字段 :Spring,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48868554/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com