Search code examples
javabean-validationhibernate-validator

Invalid escape sequencein javax.validation.constraints


I am trying to add a regExp to my Bean using Hibernate bean Validation.here is my code

@NotNull(message = "{register.pwd.invalid}")
    @Size(min = 6, max = 8, message = "{register.pwd.invalid}")
    @Pattern(regexp="^(?=.*\d)(?=.*[A-Z]).{6,8}$",message="{register.pwd.week}")
        public String getPwd()
    {
        return pwd;
    }

But using this i am getting the follwoing error

Invalid escape sequence (valid ones are  \b  \t  \n  \f  \r  \"  \'  \\ )

Seems like i am not able to escape the sequences. Is there any way or java method to handle this or do i need to do something in the regExp to handle this all


Solution

  • You need to escape the backslash in your string literal:

    regexp="^(?=.*\\d)(?=.*[A-Z]).{6,8}$"
    

    The actual string value will only have a single backslash at that point, so the regex parser will see that as "\d".

    Note that this really doesn't have anything to do with Hibernate etc. You could see the same thing just with plain strings:

    // This will give the same problem
    String x = "^(?=.*\d)(?=.*[A-Z]).{6,8}$";
    
    // Demo of fix
    String working = "^(?=.*\\d)(?=.*[A-Z]).{6,8}$";
    System.out.println(working);