Java 如何将类级验证映射到特定字段?
我有一个类级验证,如下所示:Java 如何将类级验证映射到特定字段?,java,spring,validation,Java,Spring,Validation,我有一个类级验证,如下所示: @PostalCodeValidForCountry public class Address { ... private String postalCode; private String country; } 验证的实现方式如下: @Override public boolean isValid(Address address, ConstraintValidatorContext constraintContext) { String p
@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为Address。但是,我想将此错误映射到postalCode字段。因此,我不报告ObjectError,而是报告一个FieldError,其fieldName为postalCode
是否可以在自定义验证本身中执行此操作?我希望您正在寻找的是:
constraintContext.buildConstraintViolationWithTemplate("custom_error_code").addNode("postalCode").addConstraintViolation();
这是您修改的方法的外观:
@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;
}
// this will generate a field error for "postalCode" field.
constraintContext.disableDefaultConstraintViolation();
constraintContext.buildConstraintViolationWithTemplate("custom_error_code").addNode("postalCode").addConstraintViolation();
return false;
}
请记住,只有当“isValid”方法返回false时,您才会在BindingResult对象中看到此FieldError。这看起来很有希望,最初的问题随着我们设计的更改而消失:我们现在有了一个DTO对象,可以对其进行验证,允许我们在更具体的/粒度级别而不是在较低的库本身中指定验证。我将此标记为答案,因为这是我一直在寻找的回应类型。