Kur*_*urt 2 java validation validationrules bean-validation
我想使用 Java Bean 验证来验证一个整数。它是多重验证的验证。
我目前正在使用 Spring Boot 和验证,并且系统正在使用@RestController我正在接收呼叫后的位置。
public Person addPerson(@RequestBody @Validated Person Person) {/*the code*/}
Run Code Online (Sandbox Code Playgroud)
我希望验证年龄,这些值是有效的:
age == null or age == 0 or (age >= 15 and age <= 80)
public class Person {
private Integer age;
}
Run Code Online (Sandbox Code Playgroud)
我希望能够使用 java 的当前验证约束。我需要实现我自己的约束注释吗?
这会很好,但这不起作用:
public class Person {
@Null
@Range(min=0, max=0)
@Range(min=15, max = 80)
private Integer age;
}
Run Code Online (Sandbox Code Playgroud)
您可以使用 ConstraintCoposition 对构建约束进行分组:
public class Test {
private static ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
@ConstraintComposition(CompositionType.AND)
@Min(value = 0)
@Max(value = 0)
@Target( { ElementType.ANNOTATION_TYPE } )
@Retention( RetentionPolicy.RUNTIME )
@Constraint(validatedBy = { })
public @interface ZeroComposite {
String message() default "Not valid";
Class<?>[] groups() default { };
Class< ? extends Payload>[] payload() default { };
}
@ConstraintComposition(CompositionType.OR)
@Null
@ZeroComposite
@Range(min=15, max = 80)
@Target( { ElementType.METHOD, ElementType.FIELD } )
@Retention( RetentionPolicy.RUNTIME )
@Constraint(validatedBy = { })
public @interface Composite {
String message() default "Not valid";
Class<?>[] groups() default { };
Class< ? extends Payload>[] payload() default { };
}
@Composite
private Integer age;
public Test(Integer age) {
this.age = age;
}
public static void main(String args[]) {
validate(new Test(-1));
validate(new Test(null));
validate(new Test(0));
validate(new Test(5));
validate(new Test(15));
validate(new Test(80));
validate(new Test(81));
}
private static void validate(Test t) {
Set<ConstraintViolation<Test>> violations =
factory.getValidator().validate(t);
for (ConstraintViolation<Test> cv : violations) {
System.out.println(cv.toString());
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4639 次 |
| 最近记录: |