Search code examples
javavalidationbean-validationhibernate-validator

I want to validate an object conditionally


i have an object in my class. I validate it with hibernate validator like this:

@Pattern(regexp="[0-9]{1,13}")
private String onlyNumber = null;

But, i want to validate my object when

if(onlyNumber != null && !onlyNumber.equals("")

because it is optional. And i want to do it with regular expression. Is there any way to succeed this? thanks


Solution

  • @Pattern(regexp="[0-9]{0,13}")
    

    should be sufficient. null values are always considered valid (you need @NotNull in addition to other validations to reject null). And the empty string matches the above regexp.