【问题标题】:How to add JSR 303 validation to arguments of a method如何将 JSR 303 验证添加到方法的参数
【发布时间】:2016-06-17 05:19:57
【问题描述】:

我想使用 Hibernate Validator 来验证我的方法的参数。

我尝试查找示例并查看了以下示例 JSR 303. Validate method parameter and throw exception

但是答案并不能完全解决我的问题,而且答案中的链接已过期。

这是我尝试过的示例代码。

//removing imports to reduce the length of code. 

/**
 * Created by Nick on 15/06/2016.
 */

@Component
public class ValidationService {

    @Value("${namesAllowed}")
    private String validNames;

    @Autowired
    private Validator validator;

    public boolean validateName(
            @NotEmpty
            @Pattern(regexp = ".*'.*'.*")
            @Email
            @Length(max = 10)
                    String name
    ) {

        Set<ConstraintViolation<String>> violations = validator.validate(name);

        for (ConstraintViolation<String> violation : violations) {
            String propertyPath = violation.getPropertyPath().toString();
            String message = violation.getMessage();
            System.out.println("invalid value for: '" + propertyPath + "': " + message);
        }
        List<String> namesAllowed= Arrays.asList(validNames.split(","));
        if (namesAllowed.contains(name.substring(name.indexOf(".") + 1))) {
            return true;
        }
        return false;
    }
}

}

【问题讨论】:

    标签: java spring validation hibernate-validator


    【解决方案1】:

    方法验证已被标准化为 Bean Validation 1.1 的一部分。您可以在 Hibernate Validator reference guide 中了解更多信息。

    使用 Spring,您需要配置 MethodValidationPostProcessor bean 并使用 @Validated 注释受约束的类。另外this answer 可能对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-10
      • 2014-03-13
      • 2011-10-30
      • 2018-08-15
      • 1970-01-01
      相关资源
      最近更新 更多