0

I need a custom validator in Spring Boot(version 2.7.x). My User class is defined as:

class User{
  private String email;
  private String phone;
  private String name;
  private String address;
  private String city;
  private String country;
  private String postalCode;
  //getters and setters
}

I'm trying to validate the following requirements:

  1. Either phone or email or a combination of (name+address+city+country+postalCode) is mandatory
  2. If (name+address+city+country+postalCode) is present, they should be not null.

Please help with your suggestions as to how do I go about in implementing it.

M. Deinum
  • 115,695
  • 22
  • 220
  • 224

1 Answers1

0

you can use JSR-303 valiation implementation that hibernate-validator and it is conventient to use annotation for valiate which is in package javax.validation.constraints

here is code sample that you can use @NotNull annotation above Field that mark the field should be not null

  • entity
class User{
  private String email;
  private String phone;
  private String name;
  @NotNull(message = "address should be not null")
  private String address;
  private String city;
  private String country;
  private String postalCode;
  //getters and setters
}
  • validatorUtil
@Slf4j
public class ValidatorUtil {

    static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
    public static <T>  Set<ConstraintViolation<T>> validateOne(T t , Class<?>... group) {
        Set<ConstraintViolation<T>> validateResult = validator.validate(t,group);
        return validateResult;
    }

}
  • valiatorTest
@Slf4j
public class ValiatorTest {

    @Test
    public void vailator(){
        User accountInfo = new User();
        Set<ConstraintViolation<User>> constraintViolations = ValidatorUtil.validateOne(accountInfo);
        Assertions.assertTrue(CollectionUtil.isNotEmpty(constraintViolations));
    }

}

if you build project with maven ,add hibernate-validator dependency to pom

 <properties>

        <hibernate.validator.version>6.0.14.Final</hibernate.validator.version>

    </properties>
           <dependency>
            <groupId>org.hibernate.validator</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>${hibernate.validator.version}</version>
        </dependency>

if you want learn more , please accroding to this article Which @NotNull Java annotation should I use?!

Peng
  • 653
  • 8