Bean Validation Collection of String not Blank
Asked Answered
A

4

9

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?

Armenian answered 11/11, 2014 at 8:17 Comment(1)
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.Armenian
T
9
@NotEmpty
public List<@NotBlank String> getDescriptions();
Thormora answered 25/5, 2021 at 10:40 Comment(0)
P
7

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

Pentobarbital answered 24/4, 2019 at 3:24 Comment(0)
T
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>
Tricia answered 11/11, 2014 at 8:38 Comment(0)
C
-1

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

 @NotEmpty 
 @NotBlank
 @Valid
 public List<String> getDescriptions() 
Concubine answered 11/11, 2014 at 8:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.