Java – spring validates a string list of non empty elements
I have a model class that contains a list of strings The list can be empty or contain elements If it has elements, they cannot be empty For example, suppose I have a class named questionpaper, which has a list of questionids, each of which is a string
class QuestionPaper{
private List<String> questionIds;
....
}
The paper can have zero or more questions However, if there is a problem, the ID value cannot be an empty string I am writing a microservice using springboot, hibernate, JPA and Java How should I do this verification Any help is appreciated
For example, we need to reject the following JSON input from the user
{ "examId": 1,"questionIds": [ ""," ","10103" ] }
Is there any out of the box way to achieve this, or do I have to write a custom validator for it
Solution
Custom validation comments should not be a problem:
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = NotEmptyFieldsValidator.class)
public @interface NotEmptyFields {
    String message() default "List cannot contain empty fields";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}
public class NotEmptyFieldsValidator implements ConstraintValidator<NotEmptyFields,List<String>> {
    @Override
    public void initialize(NotEmptyFields notEmptyFields) {
    }
    @Override
    public boolean isValid(List<String> objects,ConstraintValidatorContext context) {
        return objects.stream().allMatch(nef -> nef != null && !nef.trim().isEmpty());
    }
}
Usage? Simple:
class QuestionPaper{
    @NotEmptyFields
    private List<String> questionIds;
    // getters and setters
}
PS: no test logic, but I think it's good
