0

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?

Jan Wytze
  • 3,307
  • 5
  • 31
  • 51

1 Answers1

1

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.

Slava Semushin
  • 14,904
  • 7
  • 53
  • 69
  • Thanks I have written my own: https://github.com/jwz104/validation It is a long way from finishing but the base is there. – Jan Wytze Sep 20 '17 at 14:28
  • I wrote my own a few years ago too: [FieldsMatchValidator](https://github.com/php-coder/mystamps/blob/581412f565c71ecc482da5542e7ff77fe6a91a7f/src/main/java/ru/mystamps/web/support/beanvalidation/FieldsMatchValidator.java) and [UniqueLoginValidator](https://github.com/php-coder/mystamps/blob/581412f565c71ecc482da5542e7ff77fe6a91a7f/src/main/java/ru/mystamps/web/support/beanvalidation/UniqueLoginValidator.java) – Slava Semushin Sep 20 '17 at 16:36