Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate Bean inside a Bean

Tags:

java

spring

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

like image 730
SuperHacks Avatar asked Feb 17 '23 13:02

SuperHacks


1 Answers

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;

}
like image 131
Jama A. Avatar answered Feb 27 '23 23:02

Jama A.