Setting regular expression to validate URL format in Adobe CQ5

1.2k Views Asked by At

I want to validate a URL inside a textfield using Adobe CQ5, so I set up the properties regex and regexText as usual, but for some reason is not working:

                <facebook
                    jcr:primaryType="cq:Widget"
                    emptyText="http://www.facebook.com/account-name"
                    fieldDescription="Set the Facebook URL"
                    fieldLabel="Facebook"
                    name="./facebookUrl"
                    regex="/^(http://www.|https://www.|http://|https://)[a-z0-9]+([-.]{1}[a-z0-9]+)*.[a-z]{2,5}(:[0-9]{1,5})?(/.*)?$/"
                    regexText="Invalid URL format"
                    xtype="textfield"/>

So when I type inside the component I can see an error message at the console:

Uncaught TypeError: this.regex.test is not a function

To be more accurate the error comes from this line:

        if (this.regex && !this.regex.test(value)) {

I tried several regular expressions and none of them worked. I guess the problem is the regular expression itself, because in the other hand I have this other regex to evaluate email address, and it works perfectly fine:

/^[A-za-z0-9]+[\\._]*[A-za-z0-9]*@[A-za-z.-]+[\\.]+[A-Za-z]{2,4}$/

Any suggestions? Thanks in advance.

1

There are 1 best solutions below

0
On BEST ANSWER

The syntax of your regex seems to treat the forward slashes (/) as special characters. Since you want to parse a URL containing slashes, my guess is you should escape them twice like this: '\\/' instead of '/'. The result would be:

/^(http:\\/\\/www.|https:\\/\\/www.|http:\\/\\/|https:\\/\\/)[a-z0-9]+([-.]{1}[a-z0-9]+)‌​*.[a-z]{2,5}(:[0-9]{1,5})?(\\/.*)?$/

You need to escape them twice because the string to be compiled as a regex must contain '\/' to escape the slashes, but to introduce a backslash in a string you have to escape the backslash itself too.