Home > database >  Java class validation with annotation
Java class validation with annotation

Time:09-22

I'm using Spring Boot.

I'm writing a Java class and I would like to make a validation using the annotations. Something like this:

@Getter @Setter
@Validated
public class User {

    @NotBlank(message = "Username cannot be empty")
    private String username;

    @NotBlank(message = "Email address cannot be empty")
    @Email(message = "Please provide valid email address")
    private String email;

    @NotBlank(message = "First Name cannot be empty")
    private String firstName;

    @NotBlank(message = "Last Name cannot be empty")
    private String lastName;
}

I would like to rise an exception if I try to create a new object with wrong parameters. Same result if I will try to use a setter with wrong parameter.

Is it' possible? Is my code wrong?

CodePudding user response:

You can invoke validator by yourself

@Component   
class SomeComponent{

 private Validator validator;

 SomeComponent(Validator validator){
   this.validator = validator;
 }

 void validateInput(Input input) {
   
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Set<ConstraintViolation<Input>> violations = validator.validate(input);
    if (!violations.isEmpty()) {
      throw new ConstraintViolationException(violations);
    }
  }
}

You can trigger in Post Constructor method and in setters

CodePudding user response:

You can use Hibernate Validator for Annotation validations https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#validator-gettingstarted-createmodel

  • Related