如何确保列表中的各个字符串不为空或遵循特定模式
@NotNull
List<String> emailIds;我还想添加一个模式
@Pattern("\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b.")
但我可以没有it.But,我当然希望有一个约束,它将检查列表中是否有字符串为空或空白。另外,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发布于 2014-03-07 03:11:42
您可以为电子邮件字符串创建一个简单的包装类:
public class EmailAddress {
@Pattern("\b[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}\b.")
String email;
//getters and setters
}然后在现有对象中标记字段@Valid:
@NotNull
@Valid
List<EmailAddress> emailIds;然后,验证器将验证列表中的每个对象。
发布于 2014-04-03 09:08:52
您不必使用任何包装器类来验证字符串列表。只需使用validator-collection中的@EachPattern约束
@NotNull
@EachPattern(regexp="\b[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}\b.")
List<String> values;仅此而已。很简单,对吧?有关详细信息,请参阅this,因此请回答。
发布于 2014-03-07 03:02:30
在我看来,对对象使用包装类,并对方法进行自己的验证:
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
}或者,只使用列表的自定义对象
https://stackoverflow.com/questions/22233512
复制相似问题