我正在使用
Spring Hibernate Spring-MVC.
我想定义一个自定义约束,结合其他两个预定义的验证注释:@NotNull @Size,如下所示:
我想定义一个自定义约束,结合其他两个预定义的验证注释:@NotNull @Size,如下所示:
import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; @NotNull @Size(min=4) public @interface JPasswordConstraint { } // this is not correct. It's just a suggestion.
我想在我的表单模型中使用此注释.
public class ChangePasswordForm { @NotNull private String currentPass; @JPasswordConstraint private String newPass; @JPasswordConstraint private String newPassConfirm; }
UserController.java
@RequestMapping(value = "/pass",method = RequestMethod.POST) public String pass2(Model model,@Valid @modelattribute("changePasswordForm") ChangePasswordForm form,BindingResult result) { model.addAttribute("changePasswordForm",form); try { userService.changePassword(form); } catch (Exception ex) { result.rejectValue(null,"error.objec",ex.getMessage()); System.out.println(result); } if (!result.hasErrors()) { model.addAttribute("successMessage","password changed successfully!"); } return "user/pass"; }
但它不起作用.它接受少于4个字符的密码.
我怎么解决这个问题?
解决方法
这有点晚了,但结合了验证注释的技术
@L_301_1@
在撰写本文时,可能没有它,但解决方案正在跟进
@NotNull @Size(min=4) @Target({ METHOD,FIELD,ANNOTATION_TYPE }) @Retention(RUNTIME) @Constraint(validatedBy = { }) @Documented public @interface JPasswordConstraint { String message() default "Password is invalid"; Class<?>[] groups() default { }; Class<? extends Payload>[] payload() default { }; }