Search code examples
javaregexhibernatehibernate-validator

How can I do a regex pattern for Hibernate validation?


I want to use a regex @Pattern with Hibernate validation. How can I do this regex expression?

[a][b][c][d][e] is a number with 13 digits like this: 1831222132132

a - one digit, 1 or 2, nothing else;
b - from 01 to 99, it is the last 2 digits from the year, for ex 1983 => b = 83;
c - from 01 to 12;
d - from 01 to 31;
e - 6 digits;

Any help will be appreciated. Thank you!


Solution

  • To validate that in Hibernate you can use @Pattern annotation like this

    @Column(name = "myInpt")
    @Pattern(regexp = "^[12](0[1-9]|[1-9][0-9])(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])([0-9]{6})$", message = "Incorrect format")
    private String myInput;