Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding @NotNull or Pattern constraints on List<String>

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

@NotNull
List<String> emailIds;

I also want to add a pattern

@Pattern("\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b.")

but I can live without it.But I would definitely like to have a constraint which will check if any strings inside a list are null or blank. Also how would the Json schema look like

"ids": {
      "description": "The  ids associated with this.", 
    "type": "array",
        "minItems": 1,
        "items": {
        "type": "string",
         "required" :true }
 }

"required" :true does not seem to do the job
like image 344
Abhijeet Kushe Avatar asked Mar 06 '14 18:03

Abhijeet Kushe


People also ask

How do you validate a list of objects in Java?

Your list subclass would look something like this: public class ValidList<E> implements List<E> { @Valid private List<E> list; public ValidList() { this. list = new ArrayList<E>(); } public ValidList(List<E> list) { this. list = list; } // Bean-like methods, used by javax.

What is the difference between @NotNull and @NotBlank?

@NotNull : The CharSequence, Collection, Map or Array object is not null, but can be empty. @NotEmpty : The CharSequence, Collection, Map or Array object is not null and size > 0. @NotBlank : The string is not null and the trimmed length is greater than zero.

What is the difference between @NotNull and @NotEmpty?

@NotNull: a constrained CharSequence, Collection, Map, or Array is valid as long as it's not null, but it can be empty. @NotEmpty: a constrained CharSequence, Collection, Map, or Array is valid as long as it's not null, and its size/length is greater than zero.


1 Answers

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
like image 131
Brice Roncace Avatar answered Sep 20 '22 09:09

Brice Roncace