Spring Validate list of strings for non-empty elements

I have a model class that has a list of strings. The list may be empty or contain elements in it. If it has elements, these elements cannot be empty. For example, suppose I have a class called QuestionPaper that has a list of questions, each of which is a string.

class QuestionPaper{
private List<String> questionIds;
....
}

A paper may have zero or more questions. But if he has questions, id values ​​cannot be empty. I am writing a microservice using SpringBoot, Hibernate, JPA and Java. How can I do this check. Any help is appreciated.

For example, we need to reject the next json input from the user.

{ "examId": 1, "questionIds": [ "", " ", "10103" ] }

Is there any way to do this, or will I have to write a special validator for this.

+9
source share
5 answers

Custom validation annotation 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());
    }

}

Using? Simply:

class QuestionPaper{

    @NotEmptyFields
    private List<String> questionIds;
    // getters and setters
}

PS I did not check the logic, but I think it’s good.

+18
source

This may be sufficient if it is only empty or empty space.

@NotNull, @Valid, @NotEmpty

You can check example . Complete validation kit - JSR 303 provides a view that meets the requirement.

+1
source
!CollectionUtils.isEmpty(questionIds) 
   && !questionIds.stream.anyMatch(StringUtils::isEmpty())
+1

,

import org.apache.commons.collections.CollectionUtils;

    QuestionPaper question = new QuestionPaper();
    question.setQuestionIds(Arrays.asList("", " ", "10103"));

   if(CollectionUtils.isNotEmpty(question.getQuestionIds())) {
        // proceed
    } else {
        //throw exception or return
    }

nontnull notempty.

0

, , . , , , , . Java 8 Type Annotations. , . ElementTypes .

@Target({ElementType.TYPE_USE, ElementType.TYPE_PARAMETER})
public @interface SomeAnnotation {
}

TYPE_PARAMETER , , SomeClass<T>. TYPE_USE .

. .

private final Collection<@NotEmpty(message = "'questionIds' Cannot contain empty values") String> questionIds;

Spring:

- javax.validation.Validator , . JSR-303 Spring MVC, Bean Validation, Hibernate , . Spring MVC .

, , Hibernate Validator . maven .

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>6.0.10.Final</version>
</dependency>
0

Source: https://habr.com/ru/post/1654656/


All Articles