Vad1mo
Vad1mo

Reputation: 5545

Bean Validation Collection of String not Blank

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?

Upvotes: 9

Views: 12491

Answers (4)

sasha_trn
sasha_trn

Reputation: 2015

@NotEmpty
public List<@NotBlank String> getDescriptions();

Upvotes: 9

arshithp
arshithp

Reputation: 121

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()```

Upvotes: 7

Ruby Kannan
Ruby Kannan

Reputation: 251

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

 @NotEmpty 
 @NotBlank
 @Valid
 public List<String> getDescriptions() 

Upvotes: -1

Markus Malkusch
Markus Malkusch

Reputation: 7868

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>

Upvotes: 1

Related Questions