Spring Validate List of Strings for non empty elements

做~自己de王妃 提交于 2019-12-04 18:53:01

问题


I have a model class which has list of Strings. The list can either be empty or have elements in it. If it has elements, those elements can not be empty. For an example suppose I have a class called 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. But if it has questions, the id values can not be empty strings. I am writing a micro service using SpringBoot, Hibernate, JPA and Java. How can I do this validation. Any help is appreciated.

For an example we need to reject the following json input from a user.

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

Is there any out of the box way of achieving this, or will I have to write a custom validator for this.


回答1:


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.




回答2:


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.




回答3:


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



回答4:


This can easily be addressed if you use

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
    }

This will check for nontnull and notempty.



来源:https://stackoverflow.com/questions/39504205/spring-validate-list-of-strings-for-non-empty-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!