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

时间:2013-12-18 17:03:41

标签: java spring validation

我有类级别验证,如下所示:

@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 on,其地址为objectName。但是,我想将此错误映射到postalCode字段。因此,我不想报告一个ObjectError,而是报告一个fieldError,其fieldName为postalCode。

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

1 个答案:

答案 0 :(得分:2)

我希望你要找的是:

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"时才会在BindingResult对象中看到这个FieldError。方法将返回false。