kodaek98
kodaek98

Reputation: 473

How to configure bean validation programatically?

Codes where i want to use bean validation:

@Inject
private ValidatorFactory validatorFactory;
....

public Response create(@Context HttpServletRequest request) {
        ...
        Set<ConstraintViolation<UserDTO>> validate = validatorFactory.getValidator().validate(userDTO);
        validate.forEach(error-> System.err.println(error.getMessage()));
        if(validate.size() > 0){
            throw new ValidationException("userDTO is not valid!");
        }
        ...
}


public Response update(@Context HttpServletRequest request) {
        Set<ConstraintViolation<UserDTO>> validate = validatorFactory.getValidator().validate(userDTO);
        validate.forEach(error-> System.err.println(error.getMessage()));
        if(validate.size() > 0){
            throw new ValidationException("userDTO is not valid!");
        }
        ...
}

UserDTO:

public class UserDTO {
    private Integer id;
    private String userName;
    @NotNull(message = "is missing")
    private String locked;
    @Email(message = "email is not valid")
    private String email;
    @NotNull(message = "countryCode is missing")
    private String countryCode;
    ...getters-setters more variables...
}

So i have a post Http method where i want to create a user...bean validation is working if missing countrycode or locked ok or if email not valid ok...But when i want to just update for example email the validation is also run on the whole dto class...so the question is can i and how can i configure not to run on every variable each time?

Upvotes: 0

Views: 138

Answers (1)

Flown
Flown

Reputation: 11740

You should use Validator::validateProperty to check specifc properties. You can also group them and check it via Validator::validate (see here for tutorial) if there are more than one property.

Upvotes: 1

Related Questions