I have created a custom validator annotation and I want to use it only when username is not null. I have an endpoint where @RequestParam String username is not required and everything is fine there. Problem is with annotation, because it validates username regardless of the existence of a variable. I want to validate username only If username exists. Here is code:
@RequestMapping(value = "", method = RequestMethod.GET)
public ResponseEntity get( @RequestParam(value = "username", required = false) @ExistAccountWithUsername(required = false) String username) {
if (username != null) {
return getUsersByUsername(username);
}
return getAllUsers();
}
Annotation:
@Filled
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = ExistAccountWithUsernameValidator.class)
public @interface ExistAccountWithUsername {
boolean required() default true;
String message() default "There is no account with such username";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
Validator:
public class ExistAccountWithUsernameValidator implements ConstraintValidator<ExistAccountWithUsername, String> {
private UserService userService;
private boolean required;
public ExistAccountWithUsernameValidator(UserService userService) {
this.userService = userService;
}
public void initialize(ExistAccountWithUsername constraint) {
required = constraint.required();
}
public boolean isValid(String username, ConstraintValidatorContext context) {
if (!required) {
return true;
}
return username != null && userService.findByUsername(username).isPresent();
}
}
EDIT: I have added parameter. @Filled is @NotBlank and @NotNull. Updated code. It return:
"errors": [
"must not be blank",
"must not be null"
]