totothegreat
totothegreat

Reputation: 1643

How should i adjust regex for validate url to accept #?

I have this regex to validate a url:

 $scope.validUrl = function(str){
            var pattern = new RegExp('^(https?:\\/\\/)?'+ // protocol
            '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name
            '((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
            '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path
            '(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string
            '(\\#[-a-z\\d_]*)?$','i'); // fragment locator
            if(!pattern.test(str)) {
                return false;
            } else {
                return true;
            }
        };

and i want to validate this url with it:

http://coding-academy.org/#/contact

if i apply this url to the function, returns false,

Problem is the #, How should i make this work?

Upvotes: 0

Views: 89

Answers (1)

Aran-Fey
Aran-Fey

Reputation: 43136

In the port and path part of the regex, change the character class [-a-z\d%_.~+] to [-a-z\d%_.~+#].

Note that this will also match http://coding-academy.org/####/contact###. If you don't want that, change the (\/[-a-z\d%_.~+]*)* bit to (\/[-a-z\d%_.~+]*|\/#)* instead.

Upvotes: 1

Related Questions