我是 Spring 新手,正在尝试使用国际化验证消息制作验证表单。 我正在使用 JSR @Valid 注释进行登录表单验证。
我想执行以下 3 项验证:
- 检查用户名是否为空
- 检查密码是否为空。
- 检查密码与用户名是否有效。
我能够执行所有这些验证,但问题是在我的 UI 上,我得到了第三次验证以及第一次和第二次验证。
我想仅在通过第一次和第二次验证时显示第三次验证。
下面是我的jsp代码:
<label for="username"> <spring:message code="label.email" /> </label>
<form:input path="username" id="username" />
<form:errors path="username" style="color: red" />
<br />
<br />
<label for="password"> <spring:message
code="label.password" /></label>
<form:input path="password" id="password" />
<form:errors path="password" style="color: red" />
<br />
<form:errors path="authenticated" style="color: red" />
我的 Controller 代码:
@RequestMapping(value = "/login", method = {RequestMethod.POST, RequestMethod.GET})
public String authenticate(@ModelAttribute("user") @Valid User user,BindingResult result, ModelMap model, Locale locale, SessionStatus status, RedirectAttributes redirectAttrs, HttpServletRequest req){
if(result.hasErrors()){
return "home";
}
//code to validate password against username
}
我的 Bean 代码
public class User implements Serializable {
private static final long serialVersionUID = -7788619177798333712L;
@NotEmpty(message = "Please enter your username.")
private String username;
@NotEmpty(message = "Please enter your password.")
private String password;
@AssertTrue(message= "Invalid username or password")
boolean authenticated;
如果有人能在这个问题上指导我,这将是一个很大的帮助。
最佳答案
您可以使用类leven 约束而不是单独的字段进行验证。
参见Cross field validation with Hibernate Validator (JSR 303)和 How can I validate two or more fields in combination?
只需在实现 Constraint 或 ConstraintValidator 接口(interface)的 validator 类中引入您自己的注释来检查字段组合即可。
然后将注释添加到表单类。
关于java - Spring Form 中的类级别验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41968375/