简体   繁体   English

Spring Boot自定义字段验证

[英]Spring boot custom field validation

I am trying to make the following validations: 我正在尝试进行以下验证:

  • Checking in an email exists in the database. 检入电子邮件存在于数据库中。
  • Checking in an username exists in the database. 检入用户名存在于数据库中。
  • Checking if the password confirmation is entered correctly. 检查密码确认是否正确输入。

I am using a class for validation. 我正在使用一个类进行验证。 Example: 例:

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

This is all working fine until this far. 到目前为止,一切都很好。
But now I want to build in the password validation(Check if 2 password's match). 但是现在我想建立密码验证(检查2个密码是否匹配)。 I will only use this one time, so I think it is unnecessary to create a whole Annotation for this. 我只会使用一次,因此我认为没有必要为此创建一个完整的注释。
How can I do this without the use of an Annotation. 不使用注释怎么办?

The solution I found that comes closes to what I want is to use @AssertTrue on a method that validates the passwords: 我发现的解决方案与我想要的@AssertTrue ,是在验证密码的方法上使用@AssertTrue

@AssertTrue("Passwords don't match")
public boolean checkPasswords() {
    return this.password.equals(this.passwordConfirmation);
}

This works but it is not linked to a field, but it is a global error. 此方法有效,但未链接到字段,但这是全局错误。
So I can't find out to what field the Passwords don't match error belongs. 因此,我无法找到“ Passwords don't match错误属于哪个字段。 Is there a way to link the checkPasswords validation to a field? 有没有一种方法可以将checkPasswords验证链接到字段?

This works but it is not linked to a field, but it is a global error. 此方法有效,但未链接到字段,但这是全局错误。

Yes, it's a global error because you're working with a whole object. 是的,这是全局错误,因为您正在处理整个对象。

How can I do this without the use of an Annotation. 不使用注释怎么办?

I don't know such ways. 我不知道这样 You have to write your own validator in order to achieve that. 为此,您必须编写自己的验证器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM