I have a URL validator as below
(^|\s)((https?:\/\/)?[\w-]+(\.[\w-]+)+\.?(:\d+)?(\/\S*)?)
which seems to cover most bases, but one that it can't, which is to allow localhost url's
I want to allow
http://localhost:8080
or
localhost:8080
But I don't want to allow simple string like
http://google
or
google
I have a URL validator as below
(^|\s)((https?:\/\/)?[\w-]+(\.[\w-]+)+\.?(:\d+)?(\/\S*)?)
which seems to cover most bases, but one that it can't, which is to allow localhost url's
I want to allow
http://localhost:8080
or
localhost:8080
But I don't want to allow simple string like
http://google
or
google
Share
Improve this question
asked Jan 5, 2018 at 9:29
StevieBStevieB
6,55139 gold badges113 silver badges194 bronze badges
2 Answers
Reset to default 6You can use this regex to allow localhost
as a valid hostname:
(?:^|\s)((https?:\/\/)?(?:localhost|[\w-]+(?:\.[\w-]+)+)(:\d+)?(\/\S*)?)
RegEx Demo
Also you can use this RegEx
^((https?:\/\/)?(([\w-]+(?:\.[\w-]+)+)(:\d{1,5})?|([\w-]+:\d{1,5}))(\/\S*)?)$
RegEx Demo