我有以下的豆子
public class MyModel {
@NotNull
@NotEmpty
private String name;
@NotNull
@NotEmpty
private int age;
//how do you validate this?
private MySubModel subModel;
}
public class MySubModel{
private String subName;
}然后我使用@Valid注解从控制器端验证这一点。
谢谢
发布于 2013-05-13 08:36:09
您可以使用Bean验证(JSR-303)定义您自己的自定义验证,例如,这里是简单的自定义邮政编码验证,通过使用您可以轻松验证的自定义注释进行注释:
@Documented
@Constraint(validatedBy = ZipCodeValidator.class)
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ZipCode {
String message() default "zip code must be five numeric characters";
Class<?>[] groups() default {};
Class<?>[] payload() default {};
}和自定义验证类,您可以使用像<YourAnnotationClassName,TypeWhichIsBeingValidated>这样的自定义beans来代替
public class ZipCodeValidator implements ConstraintValidator<ZipCode, String> {
@Override
public void initialize(ZipCode zipCode) {
}
@Override
public boolean isValid(String string, ConstraintValidatorContext context) {
if (string.length() != 5)
return false;
for (char c : string.toCharArray()) {
if (!Character.isDigit(c))
return false;
}
return true;
}
}下面是它的用法:
public class Address{
@ZipCode
private String zip;
}发布于 2015-10-24 17:22:02
您可以尝试这样做:
public class MyModel {
@NotNull
@NotEmpty
private String name;
@NotNull
@NotEmpty
private int age;
// how do you validate this?
private MySubModel subModel;
@NotNull
@Size(min=5, max=10)
public String getSubModelSubName() {
return subModel == null ? null : subModel.getSubName();
}
}另一种可能是在内部bean中使用@Valid注释。例如:
public class MySubModel{
@NotNull
@Size(min=5, max=10)
private String subName;
}然后,你必须像这样编写你的主类:
public class MyModel {
@NotNull
@NotEmpty
private String name;
@NotNull
@NotEmpty
private int age;
// how do you validate this?
@Valid
private MySubModel subModel;
}我使用的是Spring Boot 1.2.5
https://stackoverflow.com/questions/16513179
复制相似问题