gpt4 book ai didi

java - 如何向方法的参数添加 JSR 303 验证

转载 作者:行者123 更新时间:2023-12-01 09:47:25 24 4
gpt4 key购买 nike

我想使用 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;
}
}

}

最佳答案

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

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

关于java - 如何向方法的参数添加 JSR 303 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37873638/

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