Spring 启动自定义字段验证
Spring boot custom field validation
我正在尝试进行以下验证:
- 正在签入数据库中存在的电子邮件。
- 正在签入数据库中存在的用户名。
- 正在检查密码确认是否输入正确。
我正在使用 class 进行验证。示例:
public class RegisterRequest {
@NotNull(message = "Please enter an email")
@Email(message = "Not a valid email")
@JsonProperty("email")
public String email;
@NotNull(message = "Please enter a name")
@JsonProperty("name")
public String name;
@NotNull(message = "Please enter a password")
@JsonProperty("password")
public String password;
@NotNull
@JsonProperty("password_confirmation")
public String passwordConfirmation;
}
到目前为止一切正常。
但现在我想建立密码验证(检查 2 个密码是否匹配)。我只会用一次,所以我认为没有必要为此创建一个完整的注释。
我如何在不使用注释的情况下执行此操作。
我发现接近我想要的解决方案是在验证密码的方法上使用 @AssertTrue
:
@AssertTrue("Passwords don't match")
public boolean checkPasswords() {
return this.password.equals(this.passwordConfirmation);
}
这有效,但它没有 link 编辑到字段,但它是一个全局错误。
所以我无法找出 Passwords don't match
错误属于哪个字段。
有没有办法 link 对字段进行 checkPasswords
验证?
This works but it is not linked to a field, but it is a global error.
是的,这是一个全局错误,因为您正在处理整个对象。
How can I do this without the use of an Annotation.
我不知道这样的方式。您必须编写自己的验证器才能实现这一点。
我正在尝试进行以下验证:
- 正在签入数据库中存在的电子邮件。
- 正在签入数据库中存在的用户名。
- 正在检查密码确认是否输入正确。
我正在使用 class 进行验证。示例:
public class RegisterRequest {
@NotNull(message = "Please enter an email")
@Email(message = "Not a valid email")
@JsonProperty("email")
public String email;
@NotNull(message = "Please enter a name")
@JsonProperty("name")
public String name;
@NotNull(message = "Please enter a password")
@JsonProperty("password")
public String password;
@NotNull
@JsonProperty("password_confirmation")
public String passwordConfirmation;
}
到目前为止一切正常。
但现在我想建立密码验证(检查 2 个密码是否匹配)。我只会用一次,所以我认为没有必要为此创建一个完整的注释。
我如何在不使用注释的情况下执行此操作。
我发现接近我想要的解决方案是在验证密码的方法上使用 @AssertTrue
:
@AssertTrue("Passwords don't match")
public boolean checkPasswords() {
return this.password.equals(this.passwordConfirmation);
}
这有效,但它没有 link 编辑到字段,但它是一个全局错误。
所以我无法找出 Passwords don't match
错误属于哪个字段。
有没有办法 link 对字段进行 checkPasswords
验证?
This works but it is not linked to a field, but it is a global error.
是的,这是一个全局错误,因为您正在处理整个对象。
How can I do this without the use of an Annotation.
我不知道这样的方式。您必须编写自己的验证器才能实现这一点。