![](/img/trans.png)
[英]How to add ConstraintViolations to list element at index i with custom ConstraintValidator
[英]how to create a ConstraintValidator for List
我有一個簡單的驗證器來驗證String值是否是預定義列表的一部分:
public class CoBoundedStringConstraints implements ConstraintValidator<CoBoundedString, String>
{
private List<String> m_boundedTo;
@Override
public void initialize(CoBoundedString annotation)
{
m_boundedTo = FunctorUtils.transform(annotation.value(), new ToLowerCase());
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context)
{
if (value == null )
{
return true;
}
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate("should be one of " + m_boundedTo).addConstraintViolation();
return m_boundedTo.contains(value.toLowerCase());
}
}
例如,它將驗證:
@CoBoundedString({"a","b" })
public String operations;
我想創建一個驗證器對於一個字符串列表來驗證這樣的事情:
@CoBoundedString({"a","b" })
public List<String> operations = new ArrayList<String>();
我試過這個:
public class CoBoundedStringListConstraints implements ConstraintValidator<CoBoundedString, List<String>>
{
private CoBoundedString m_annotation;
@Override
public void initialize(CoBoundedString annotation)
{
m_annotation = annotation;
}
@Override
public boolean isValid(List<String> value, ConstraintValidatorContext context)
{
if (value == null )
{
return true;
}
CoBoundedStringConstraints constraints = new CoBoundedStringConstraints();
constraints.initialize(m_annotation);
for (String string : value)
{
if (!constraints.isValid(string, context))
{
return false;
}
}
return true;
}
}
問題是,如果列表包含2個或更多非法值,則只有一個(第一個)約束違規。 我希望它不止一個。 我該怎么辦?
您當前的代碼有2個問題:
在你的CoBoundedStringListConstraints
的isValid
方法中,你應該像這樣迭代給定列表的所有元素(設置一個合適的allValid
標志):
@Override
public boolean isValid(List<String> value,
ConstraintValidatorContext context) {
if (value == null) {
return true;
}
boolean allValid = true;
CoBoundedStringConstraints constraints = new CoBoundedStringConstraints();
constraints.initialize(m_annotation);
for (String string : value) {
if (!constraints.isValid(string, context)) {
allValid = false;
}
}
return allValid;
}
第二個是約束違規的equals
實現( javax.validation.Validator.validate()
返回一個集合! )。 當你總是輸入相同的消息( should be one of [a, b]
)時,該集合仍然只包含1個元素。 作為解決方案,您可以將當前值添加到消息(類CoBoundedStringConstraints
):
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (value == null) {
return true;
}
if (!m_boundedTo.contains(value)) {
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(
value + " should be one of " + m_boundedTo)
.addConstraintViolation();
return false;
}
return true;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.