SuperHacks
SuperHacks

Reputation: 49

Validate Bean inside a Bean

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

Upvotes: 4

Views: 1253

Answers (2)

Sobrino
Sobrino

Reputation: 541

You can try this:

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();
    }
}

Another possibility is to used the @Valid annotation with your inner bean. For example:

public class MySubModel{

  @NotNull
  @Size(min=5, max=10)
  private String subName;

}

Then, you have to code your main class like this:

public class MyModel {

    @NotNull
    @NotEmpty
    private String name;

    @NotNull
    @NotEmpty
    private int age;

    // how do you validate this?
    @Valid
    private MySubModel subModel;

}

I'm using Spring Boot 1.2.5

Upvotes: 4

Jama A.
Jama A.

Reputation: 16079

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;

}

Upvotes: 4

Related Questions