Search code examples
regexparsley

How to escape double quote in parsley data-parsley-pattern?


I am using parsley for javascript validation. My current regex pattern is

data-parsley-pattern="/^[0-9a-zA-Z\!\@\#\$\%\^\&\*\(\)\-\_\+\?\'\.\,\/\\r\n ]+$/"

How to add double quote in my pattern. I have added \" to pattern

data-parsley-pattern="/^[0-9a-zA-Z\!\@\#\$\%\^\&\*\(\)\-\_\+\?\'\"\.\,\/\\r\n ]+$/"

But it is not working.


Solution

  • Note that you overescaped the pattern, almost all the chars you escaped are not special in a character class.

    Next, you may shorten the code if you use a string pattern. See Parseley docs:

    data-parsley-pattern="\d+"

    Note that patterns are anchored, i.e. must match the whole string. Parsley deviates from the standard for patterns looking like /pattern/{flag}; these are interpreted as literal regexp and are not anchored.

    That means you do not need ^ and $ if you define the pattern without regex delimiters, /.

    As for the quotation marks, you may use a common \xXX notation.

    You may use

    data-parsley-pattern="[0-9a-zA-Z!@#$%^&*()_+?\x27\x22.,/\r\n` -]+"
    

    or

    data-parsley-pattern="/^[0-9a-zA-Z!@#$%^&*()_+?\x27\x22.,/\r\n` -]+/$"
    

    where \x27 is ' and \x22 is ".

    Note that - at the end of the character class is a safe placement for a literal hyphen where you do not have to escape it.