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). 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("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.
Is there a way to link the checkPasswords
validation to a field?