2

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

Hardy
  • 18,659
  • 3
  • 49
  • 65
devgirl
  • 39
  • 1
  • 10

1 Answers1

2
@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.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • Yes you' re right but actually my string can get "" value and i want to reject validation in this case too. – devgirl Feb 11 '15 at 13:11
  • Yes, so? Have you tried the above? As I said: the empty string matches the above regexp. So the empty string is a valid value. And that's what you want. – JB Nizet Feb 11 '15 at 13:14
  • sorry, i thought it was the same as mine. Yes it tried and it worked. Thank you !! – devgirl Feb 11 '15 at 13:19