0
我有一个类级验证,像这样:如何将类级别验证映射到特定字段?
@PostalCodeValidForCountry
public class Address
{
...
private String postalCode;
private String country;
}
验证实现像这样:
@Override
public boolean isValid(Address address, ConstraintValidatorContext constraintContext)
{
String postalCode = address.getPostalCode();
String country = address.getCountry();
String regex = null;
if (null == country || Address.COUNTRY_USA.equals(country))
{
regex = "^[0-9]{5}$";
}
else if (Address.COUNTRY_CANADA.equals(country))
{
regex = "^[A-Za-z][0-9][A-Za-z] [0-9][A-Za-z][0-9]$";
}
Pattern postalPattern = Pattern.compile(regex);
Matcher matcher = postalPattern.matcher(postalCode);
if (matcher.matches())
{
return true;
}
return false;
}
目前,当我得到的BindingResult从失败的验证结果的误差是ObjectError上与地址的objectName。但是,我想将此错误映射到postalCode字段。因此,我不想报告一个ObjectError,而是想报告一个FieldError,其中包含一个postalCode的fieldName。
是否有可能在自定义验证本身内做到这一点?
这看起来很有希望,最初的问题随着我们设计的变化而消失:我们现在有一个DTO对象,我们进行验证,允许我们在更具体/粒度级别而不是在较低库中指定验证本身。我将此标记为答案,因为这是我正在寻找的答案类型。 – Noremac