Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm using following regex for validate a url,

jQuery.validator.addMethod("url_validation", function (value, element) {
return this.optional(element) || /^(([http|https|HTTPS|HTTP]+:\/\/))?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/i.test(value);
}, "error");

This regex working fine. But when I validate http://www.alfaromeo.com/com/#/home , it says the url is invalid. When I enable #, the regex fail to validate some validations. So, can anyone give a suggestion to modify this regex to validate #, which is inside a url.

I refered regular expressions how to validate a URL to get this regex.

Thanx.

share|improve this question
add comment (requires an account with 50 reputation)

1 Answer

up vote 0 down vote accepted
^(([http|https|HTTPS|HTTP]+:\/\/))?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([#-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$

I changed

(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)

to

(\/([#-+_~.\d\w]|%[a-fA-f\d]{2,2})*)

Even so, don't expect it to work on every URL you might throw at it...

share|improve this answer
I stole this, and it broke on a comma (,) in the query string. – user1003221 May 17 '12 at 23:20
As I said, it's likely that it won't work on every possible URL. In my answer I've just modified the regex to work on the URL provided by the OP. – civilu Jul 9 '12 at 12:25
add comment (requires an account with 50 reputation)

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.