21

我试图将多个 @Pattern 注释应用于单个字段:

@Pattern(regexp = "(?=.*[0-9])", message = "Password must contain one digit.")
@Pattern(regexp = "(?=.*[a-z])", message = "Password must contain one lowercase letter.")
@Pattern(regexp = "(?=.*[A-Z])", message = "Password must contain one uppercase letter.")
@Pattern(regexp = "(?=\S+$)", message = "Password must contain no whitespace.")
private String password;

但是,我不能这样做。我希望每个违反密码字段的正则表达式约束的消息。这可能吗?

我的替代方法是使用 JSF 2.0 f:validatorRegex 标签。

4

4 回答 4

41

您可以使用的内部@List注释@Pattern

@Pattern.List({
    @Pattern(regexp = "(?=.*[0-9])", message = "Password must contain one digit."),
    @Pattern(regexp = "(?=.*[a-z])", message = "Password must contain one lowercase letter."),
    @Pattern(regexp = "(?=.*[A-Z])", message = "Password must contain one uppercase letter."),
    @Pattern(regexp = "(?=\\S+$)", message = "Password must contain no whitespace.")
})
private String password;
于 2013-04-26T20:19:20.907 回答
4

Gunnar 的解决方案对我不起作用......他的正则表达式中的'.+' 似乎丢失了。但是,我正在使用 Michal 的 patternList,它对我来说就像一个魅力。(播放 2.3.x / Ebean-ORM)

@Pattern.List({
        @Pattern(regexp = "(?=.*[0-9]).+", message = "Password must contain one digit."),
        @Pattern(regexp = "(?=.*[a-z]).+", message = "Password must contain one lowercase letter."),
        @Pattern(regexp = "(?=.*[A-Z]).+", message = "Password must contain one upper letter."),
        @Pattern(regexp = "(?=.*[!@#$%^&*+=?-_()/\"\\.,<>~`;:]).+", message ="Password must contain one special character."),
        @Pattern(regexp = "(?=\\S+$).+", message = "Password must contain no whitespace.")
})
@Constraints.Required()
public String password1;
于 2016-01-22T09:04:56.680 回答
2

您可能想研究约束组合。您将为每个由@Pattern 注解组成的密码约束构建一个注解,然后最后使用之前定义的四个构建一个组合注解。这不需要额外的 java 代码。

http://docs.jboss.org/hibernate/validator/5.0/reference/en-US/html_single/#validator-customconstraints-compound

否则,构建(使用随附的 java 代码)一个名为 @PasswordValidator 的自定义注解。

我倾向于喜欢组合验证器,因为它使验证注释的目的明确,而不是有许多不相交的注释。

于 2013-04-26T18:27:27.447 回答
2

我修改了 Gunnar 答案并编写了复合约束,现在这似乎可以在 4 个单元测试中正常工作:

@NotNull
@Size(min=6, max=45)
@Pattern.List({
    @Pattern(regexp = "(?=.*[0-9]).+", message = "Password must contain one digit."),
    @Pattern(regexp = "(?=.*[a-z]).+", message = "Password must contain one lowercase letter."),
    @Pattern(regexp = "(?=.*[A-Z]).+", message = "Password must contain one uppercase letter."),
    @Pattern(regexp = "(?=.*[!@#$%^&*+=?-_()/\"\\.,<>~`;:]).+", message ="Password must contain one special character."),
    @Pattern(regexp = "(?=\\S+$).+", message = "Password must contain no whitespace.")
})
@Constraint(validatedBy = {}) // constraints composition
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface StrongPassword {

     String message() default "Password doesn't match bean validation constraints.";
     Class<?>[] groups() default {};
     Class<? extends Payload>[] payload() default {};
}
于 2015-06-04T17:19:42.947 回答