2013-12-18 50 views
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。

是否有可能在自定义验证本身内做到这一点?

回答

1

我希望你正在寻找的是这样的:

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

记住,你会看到这个FieldError只BindingResult对象如果你的“isValid”方法将返回false。

+0

这看起来很有希望,最初的问题随着我们设计的变化而消失:我们现在有一个DTO对象,我们进行验证,允许我们在更具体/粒度级别而不是在较低库中指定验证本身。我将此标记为答案,因为这是我正在寻找的答案类型。 – Noremac

相关问题