Hibernate 验证器 REGEX 模式不起作用

问题描述 投票:0回答:0

我正在使用休眠验证来验证我从 Quarkus REST API 中的请求中收到的实体。我正在尝试通过对

@Pattern
实体的 password 字段使用
User
注释来为创建用户添加快速简单的密码验证。它看起来像这样:

@Entity
@Table(name = "users")
public class User extends BaseEntity {
    public static final int MIN_PASSWORD_LENGTH = 8;
    public static final int MAX_PASSWORD_LENGTH = 20;
    public static final String PASSWORD_PATTERN = 
        "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#&()–[{}]:;',?/*~$^+=<>]).{8,20}$";
    
    // other fields...

    @Length(min = MIN_PASSWORD_LENGTH, max = MAX_PASSWORD_LENGTH)
    @NotBlank(message = "The password field cannot be empty or blank.")
    @Pattern(regexp = PASSWORD_PATTERN, message = "The given password does not match the rules.")
    @Column(name = "password", length = 256, nullable = false)
    private String password;

    //get/set...
}

所以我使用的正则表达式模式是:

^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#&()–[{}]:;',?/*~$^+=<>]).{8,20}$

这显然对应于:

  • 至少一位数
  • 至少一个小写字符
  • 至少一个大写字符
  • 至少一个特殊字符 (!@#&()–[{}]:;',?/*~$^+=<>)
  • 长度在 8 到 20 个字符之间

对于 Java REGEX 引擎,这在 https://regex101.com/ 上工作得很好,测试密码如下:

W4schb43r1?!

但是,hibernate 验证器在我的端点为相同的密码抛出错误,因为它显然与给定的模式不匹配。为什么休眠验证器不能正确匹配密码?

(由 hibernate ConstrainViolationException 触发的已解析响应):

{
  "title": "Constraint Violation",
  "status": 400,
  "violations": [
    {
      "field": "password",
      "message": "The given password does not match the rules."
    }
  ]
}
java hibernate hibernate-validator
© www.soinside.com 2019 - 2024. All rights reserved.