Completing JSR 303 Validation

How can I override the email check for AuthorizedUser in the following situation:

public class Account { @Length(min = 1, max = 100, message = "'Email' must be between 1 and 100 characters in length.") @NotNull(message = "'Email' must not be empty.") protected String email; @Length(min = 1, max = 50, message = "'Name' must be between 1 and 50 characters in length.") private String name; } public class AuthorizedUser extends Account { @Length(min = 1, max = 40, message = "'Field' must be between 1 and 50 characters in length.") private String field; } 

I know that I could β€œcrack” the solution by overriding the email address in the installer on AuthorizedUser by doing the following:

 @Override public void setEmail(String email) { this.email = email; super.setEmail(" "); } 

It just feels dirty ... Is it possible to override it without writing a custom validator?

I tried moving @Valid to setter in a superclass and leaving it in an overridden field, but I still get a message from the superclass that it is empty. Is there a lazier way to do this?

+6
source share
1 answer

Since restrictions are aggregated through inheritance, a better solution might be to change the inheritance hierarchy like this:

 public class BasicAccount { protected String email; @Length(min = 1, max = 50, message = "'Name' must be between 1 and 50 characters in length.") private String name; } public class EmailValidatedAccount extends BasicAccount { @Length(min = 1, max = 100, message = "'Email' must be between 1 and 100 characters in length.") @NotNull(message = "'Email' must not be empty.") @Override public String getEmail() { return email; } } public class AuthorizedUser extends BasicAccount { @Length(min = 1, max = 40, message = "'Field' must be between 1 and 50 characters in length.") private String field; } 
+3
source

Source: https://habr.com/ru/post/895355/


All Articles