Adding @NotNull or Pattern constraints on List

前端 未结 4 1936
失恋的感觉
失恋的感觉 2020-12-20 16:00

How can we ensure the individual strings inside a list are not null/blank or follow a specific pattern

@NotNull
List emailIds;
相关标签:
4条回答
  • 2020-12-20 16:24

    You can create a simple wrapper class for the e-mail String:

    public class EmailAddress {
    
        @Pattern("\b[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}\b.")
        String email;
    
        //getters and setters
    }
    

    Then mark the field @Valid in your existing object:

    @NotNull
    @Valid
    List<EmailAddress> emailIds;
    

    The validator will then validate each object in the list.

    0 讨论(0)
  • 2020-12-20 16:27

    In my opinion, use a wrapper class for the object, and have your own verification on the methods:

    public class ListWrapper<E> {
    
        private List<E> list = new ArrayList<>();
        private Pattern check = /*pattern*/;
    
        public boolean add(E obj) {
            if (this.verify(obj)) {
                return list.add(obj);
            }
            return false;
        }
    
        //etc
    
        public boolean verify(E obj) {
            //check pattern and for null
        }
    

    Alternatively, just use a custom object for the list

    0 讨论(0)
  • 2020-12-20 16:41

    You don’t have to use any wrapper class just to validate a list of strings. Just use @EachPattern constraint from validator-collection:

    @NotNull
    @EachPattern(regexp="\b[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}\b.")
    List<String> values;
    

    And that’s all. Easy, right? See this SO answer for more information.

    0 讨论(0)
  • 2020-12-20 16:44

    Bean validation 2.0 (Hibernate Validator 6.0.1 and above) supports validating container elements by annotating type arguments of parameterized types. Example:

    List<@Positive Integer> positiveNumbers;
    

    Or even (although a bit busy):

    List<@NotNull @Pattern(regexp="\\b[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}\\b") String> emails;
    

    References:

    • http://beanvalidation.org/2.0/
    • https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#_with_code_list_code
    0 讨论(0)
提交回复
热议问题