8

I have a collection of strings, now I want to make sure that not only the collection is not empty but also each string in that collection does not contain a blank input.

 @NotEmpty
 public List<String> getDescriptions() // not empty collection


 @NotEmpty @NotBlank
 public List<String> getDescriptions() // NotBlank isn't applicable on collections 

Is there a way other then to wrap the string into a class or create a custom @NotBlankCollectionEntries?

leppie
  • 115,091
  • 17
  • 196
  • 297
Vad1mo
  • 5,156
  • 6
  • 36
  • 65
  • it is not a duplicate! IMO, The question assumes the object in the collection is not an primitive and thus can hold constraints. I can't add a valid constraint in string without wrapping it. – Vad1mo Nov 11 '14 at 10:21

4 Answers4

6

You could use something like this:

@NotNull
@Size(min = 1)
public List<@NotBlank @Size(max = 123) String> getDescriptions() // not empty collection


@NotNull
@Size(min = 1)
public List<@NotBlank @Size(max = 123)> getDescriptions()```

arshithp
  • 111
  • 1
  • 8
6
@NotEmpty
public List<@NotBlank String> getDescriptions();
sasha_trn
  • 1,935
  • 2
  • 23
  • 30
1

You can extend the hibernate constraint @NotBlank with a further implementation of ConstraintValidator<NotBlank, List<String>>. This is described in 8.1.2. Overriding constraint definitions in XML. This new validator can be concatenated to the existing built-in validators with the XML element <constraint-definition> in your META-INF/validation.xml file:

<constraint-definition annotation="org.hibernate.validator.constraints.NotBlank">
    <validated-by include-existing-validators="true">
        <value>com.acme.app.constraint.NotBlankValidatorForStringList</value>
    </validated-by>
</constraint-definition>
Markus Malkusch
  • 7,738
  • 2
  • 38
  • 67
-1

Annotate the field with @Valid annotation to validate the elements inside the collection.

 @NotEmpty 
 @NotBlank
 @Valid
 public List<String> getDescriptions() 
Ruby Kannan
  • 251
  • 1
  • 6