I have following Beans
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;
}
Then I use @Valid annotation to validate this from controller side.
Thank you
You can define your own custom validation with Bean Validation (JSR-303), for example here is simple custom zip code validation, by annotating with your custom annotation you can easily validate:
@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 {};
}
And custom validation class, instead of , you can use your custom beans like <YourAnnotationClassName,TypeWhichIsBeingValidated>
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;
}
}
And here is the usage of it:
public class Address{
@ZipCode
private String zip;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With