Java 在 List<String> 上添加 @NotNull 或 Pattern 约束

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22233512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 14:29:31  来源:igfitidea点击:

Adding @NotNull or Pattern constraints on List<String>

javajsonvalidationhibernate-validatorjsr

提问by Abhijeet Kushe

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.")

@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

但我可以没有它。但我绝对希望有一个约束来检查列表中的任何字符串是否为空或空白。另外 Json 模式会是什么样子

"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

采纳答案by ach

You can create a simple wrapper class for the e-mail String:

您可以为电子邮件字符串创建一个简单的包装类:

public class EmailAddress {

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

    //getters and setters
}

Then mark the field @Validin your existing object:

然后标记@Valid现有对象中的字段:

@NotNull
@Valid
List<EmailAddress> emailIds;

The validator will then validate each object in the list.

然后验证器将验证列表中的每个对象。

回答by Rogue

In my opinion, use a wrapper class for the object, and have your own verification on the methods:

在我看来,对对象使用包装类,并对方法进行自己的验证:

public class ListWrapper<E> {

    private List<E> list = new ArrayList<>();
    private Pattern check = /*pattern*/;

    public boolean add(E obj) {
        if (this.verify(obj)) {
            return list.add(obj);
        }
        return false;
    }

    //etc

    public boolean verify(E obj) {
        //check pattern and for null
    }

Alternatively, just use a custom object for the list

或者,只需为列表使用自定义对象

回答by Jakub Jirutka

You don't have to use any wrapper class just to validate a list of strings. Just use @EachPatternconstraint from validator-collection:

您不必使用任何包装类来验证字符串列表。只需使用@EachPattern来自验证器集合的约束:

@NotNull
@EachPattern(regexp="\b[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}\b.")
List<String> values;

And that's all. Easy, right? See thisSO answer for more information.

就这样。很简单,对吧?有关更多信息,请参阅SO 答案。

回答by Brice Roncace

Bean validation 2.0 (Hibernate Validator 6.0.1 and above) supports validating container elements by annotating type arguments of parameterized types. Example:

Bean 验证 2.0(Hibernate Validator 6.0.1 及更高版本)支持通过注释参数化类型的类型参数来验证容器元素。例子:

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:

参考: