Spring Validate List of Strings for non empty elements

Custom validation annotation shouldn't 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
}

P.S. Didn't test the logic, but I guess it's good.


These might suffice the need, if it is only on null or empty space.

@NotNull, @Valid, @NotEmpty

You can check with example. Complete set of validations - JSR 303 give an idea which suits the requirement.


I just had similar case to solve

class QuestionPaper {

    @NotEmpty
    private List<@NotBlank String> questionIds;

    // getters and setters
}

If List is of Integers, then go as below

class QuestionPaper {

    @NotEmpty
    private List<@Min(0) Integer> questionIds;

    // getters and setters
}