【问题标题】:spring combine two validation annotations in onespring 将两个验证注释合二为一
【发布时间】:2016-02-02 16:52:21
【问题描述】:

我正在使用 Spring+Hibernate+Spring-MVC
我想定义一个结合其他两个预定义验证注释的自定义约束:@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 个字符的密码。
我该如何解决这个问题?

【问题讨论】:

  • @JPasswordConstraint 如何得到验证?
  • 它不起作用!我想实现这样的目标。这是不正确的
  • 您使用的是哪个版本的 Spring?
  • 春季版:4.1.7.RELEASE

标签: java spring validation spring-mvc annotations


【解决方案1】:

你可以添加

@ConstraintComposition

默认情况下谁在 AND 如果有一天你想要@NotNull 或@Size 你加

@ConstraintComposition(OR)

编辑:这是一个将@Pattern(regexp = "[a-z]")@Size(min = 2, max = 3)

@ConstraintComposition(OR)
@Pattern(regexp = "[a-z]")
@Size(min = 2, max = 3)
@ReportAsSingleViolation
@Target({ METHOD, FIELD })
@Retention(RUNTIME)
@Constraint(validatedBy = { })
public @interface PatternOrSize {
    String message() default "";

 Class<?>[] groups() default { };

 Class<? extends Payload>[] payload() default { };

}

【讨论】:

  • 嗯?你能说得更具体些吗
【解决方案2】:

这有点晚了,但是在

中描述了组合验证注释的技术

https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/?v=5.4#section-constraint-composition

在撰写本文时它可能不可用,但解决方案如下

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

【讨论】:

    猜你喜欢
    • 2016-05-15
    • 1970-01-01
    • 2013-05-14
    • 1970-01-01
    • 2019-07-13
    • 1970-01-01
    • 2011-09-02
    • 1970-01-01
    • 2015-12-30
    相关资源
    最近更新 更多