views:

74

answers:

2

I'm trying to transfer the following URL validation function from my PHP code to my javascript code:

   this.validate_url = function(field)
    {
        var pattern = new RegExp("^((ht|f)tp(s?)\:\/\/|~/|/)?([\w]+:\w+@)?([a-zA-Z]{1}([\w\-]+\.)+([\w]{2,5}))(:[\d]{1,5})?((/?\w+/)+|/?)(\w+\.[\w]{3,4})?((\?\w+=\w+)?(&\w+=\w+)*)?");
        var val = $("#" + field).val();

        return pattern.test(val);
    }

And this gives me the error:

invalid quantifier ?w+=w+)?(&w+=w+)*)?

How can I fix this?

+2  A: 

Since backslash is an escaping character in JavaScript, you'll have to escape that to write it in a string:

var pattern = new RegExp("^((ht|f)tp(s?)\\:\\/\\/|~/|/)?([\\w]+:\\w+@)?([a-zA-Z]{1}([\\w\\-]+\\.)+([\\w]{2,5}))(:[\\d]{1,5})?((/?\\w+/)+|/?)(\\w+\\.[\\w]{3,4})?((\\?\\w+=\\w+)?(&\\w+=\\w+)*)?");
David Hedlund
+3  A: 
Gumbo
+1 for use of the literal syntax. It avoids (some) of the pain of escaping
Matt