字符串的 Bean 验证集合不为空

Vad*_*imo 5 java bean-validation

我有一个字符串集合,现在我想确保不仅集合不为空,而且该集合中的每个字符串都不包含空白输入。

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


 @NotEmpty @NotBlank
 public List<String> getDescriptions() // NotBlank isn't applicable on collections 
Run Code Online (Sandbox Code Playgroud)

除了将字符串包装到类中或创建自定义@NotBlankCollectionEntries 之外,还有其他方法吗?

sas*_*trn 8

@NotEmpty
public List<@NotBlank String> getDescriptions();
Run Code Online (Sandbox Code Playgroud)


ars*_*thp 5

你可以使用这样的东西:

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

Run Code Online (Sandbox Code Playgroud)


Mar*_*sch 1

@NotBlank您可以通过进一步实现来扩展 hibernate 约束ConstraintValidator<NotBlank, List<String>>。这在 8.1.2 中有描述。覆盖 XML 中的约束定义这个新的验证器可以通过META-INF/validation.xml<constraint-definition>文件中的XML 元素连接到现有的内置验证器:

<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>
Run Code Online (Sandbox Code Playgroud)