Home > other >  Java Validate Field Conditional On Class Level
Java Validate Field Conditional On Class Level

Time:09-17

Say I have the following Pojos and constraints.

public class Pojo1 {
    @NotNull
    private String field1;
    @NotNull
    private String field2; // <--- I only want this NotNull in Pojo3.java but not in Pojo2.java
}

public class Pojo2 {
    @Valid
    private Pojo1 pojo1;
}

public class Pojo3 {
    @Valid
    private Pojo1 pojo1;
    @Valid
    private Pojo2 pojo2;
}

I want Pojo1.field2 to be validated ONLY under Pojo3 but not Pojo2. In other words, the following JSON should pass validation

{
   "pojo1": {
      "field1": "something",
      "field2": "something"
   },
   "pojo2": {
      "pojo1": {
         "field1": "something"
      }
   }
}

CodePudding user response:

Try replacing Pojo1.field2 validation with custom validation on Pojo3 for example like this:

public class Pojo1 {

    @NotNull
    private String field1;

    // @NotNull // don't validate it generally
    private String field2;
}
public class Pojo2 {
    @Valid
    private Pojo1 pojo1;
}

public class Pojo3 {

    @Valid
    private Pojo1 pojo1;

    @Valid
    private Pojo2 pojo2;

    @javax.validation.constraints.AssertTrue
    public boolean isPojo1Valid() {
        return pojo1 == null || pojo1.getField2() != null;
    }
}
  • Related