gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 04:06:16 24 4
gpt4 key购买 nike

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

@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。但是,我想将此错误映射到邮政编码字段。因此,我不想报告 ObjectError,而是报告 fieldName 为 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。

关于java - 如何将类级别验证映射到特定字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20664133/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com