如何将类级别验证映射到特定字段



>我有一个这样的类级验证:

@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;
}

目前,当我获得绑定结果时,由失败的验证导致的错误是具有对象地址名称的对象错误。但是,我想将此错误映射到 postalCode 字段。因此,与其报告ObjectError,不如报告字段名称为postalCode的FieldError。

是否可以在自定义验证本身中执行此操作?

我希望您正在寻找的是:

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。

最新更新