0

I have a search criteria for a Project model. A Project can be searched using an id or project name.

@Data
@Builder
public class ProjectSearchCriteria {
    @IsNumberValidatorConstraint(message = "invalid input for id")
    private String id;
    private String projectName;
}

I have also created a custom validator to check whether the id is a number (Number validation). This is also working perfectly.

But my question is that is there any possibility for me to tell spring; to perform Number validation only if id is not null?

e.g:

http://localhost:8081/api/projects?id=1 (id needs to be validated)

http://localhost:8081/api/projects?projectName=project1 (No need to validate the id)

Any ideas on how I can get this working?

Cheers

Shanka Somasiri
  • 581
  • 1
  • 8
  • 30
  • 1
    Why don't you add `if(value == null) return true;` to your custom validator? Which makes it valid if the id is null. – Toni Feb 26 '23 at 08:29

1 Answers1

0

Created a custom validator to return true if number and also for null.

public class IsNumberOrNullValidator implements ConstraintValidator<IsNumberValidatorOrNullConstraint, String> {
    @Override
    public boolean isValid(String number, ConstraintValidatorContext cxt) {
        if(number == null){
            return true;
        }
        return NumberUtils.isParsable(number);
    }
}
Shanka Somasiri
  • 581
  • 1
  • 8
  • 30
  • yes. but i thought the question was to have spring not do the validation if it was null. this actually *does* the validation but returns true if it's null. – Mag Musik Feb 26 '23 at 10:30