jeudi 13 février 2020

How to validate that least one field is not null when the field is private

I am trying to create a custom javax validator that would check if at least one of the mention fields are non-null. I tried following this example, Hibernate validation annotation - validate that at least one field is not null

Swapping out the Apache commons library with reflection. As I don't have access for that in this project, and instead need to use hiberate validator, javax validator, or anything that comes built-in

Object to be validated is structured like this.

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
@AtleastOneFilled(fieldNames = {"username", "email"},
    groups = {TestGroup.class}
    , message = ValidationsConstants.MISSING_REQUIRED_USERNAME_EMAIL)
public class TestClass {


  String username;

  String email;

  }

and the validator's isValid command is programmed as such

  @Override
  public boolean isValid(Object object, ConstraintValidatorContext context) {
    if (object == null)
      return true;

    try {

      for (String fieldName: fieldNames){
        Field property = object.getClass().getDeclaredField(fieldName);
        //not allowed to use setAccessible.
        if (property.get(object)!=null) return true; // throws IllegalAccessException
      }

      return false;

    } catch (Exception e) {

      return false;
    }
  }
}




Aucun commentaire:

Enregistrer un commentaire