0

I want a regex for validate url through Javascript. So here the samples of urls that I want to be validated

https://www.google.com

https://google.com

http://www.google.com

http://google.com

google.com

www.google.com

So to achieve that I have made the regex like this

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

But its not matching all the patterns what I have shared. So can someone tell me what exactly the regex should be like?

No restriction should be there in the domain name. It might come with .in, .edu, .xyz, .com etc.

NewUser
  • 12,713
  • 39
  • 142
  • 236
  • Check this: https://stackoverflow.com/questions/1410311/regular-expression-for-url-validation-in-javascript or [this one](https://stackoverflow.com/questions/26093545/how-to-validate-domain-name-using-regex/38578855) – anubhava Mar 29 '21 at 05:47
  • @anubhava any domain name it should be like .in, .edu, .xyz, .com etc. No restriction should be there. – NewUser Mar 29 '21 at 05:55
  • That works fine but the thing is it is also validating this one `www.dgsds.com.ccxx` which is an invalid url. – NewUser Mar 29 '21 at 06:08
  • 1
    What is definition of invalid URL here? I guess you will need exhaustive list of top domains to validate your domain. – anubhava Mar 29 '21 at 06:09
  • I am not telling about the list. The url should be max 2 dots(.), more than 2 dots in an url should be an invalid one I think. – NewUser Mar 29 '21 at 06:11
  • So `www.bbc.co.uk` will be invalid? – anubhava Mar 29 '21 at 06:12
  • Ok max 2-3 is fine. As I see in the url what you have shared seems to a valid one. But more than that doesn't look like a valid url. – NewUser Mar 29 '21 at 06:14
  • Try this: `/^(?:https?:\/\/)?(?:www\.)?(?:[\w-]+\.)+[a-z]{1,3}$/gmi` – anubhava Mar 29 '21 at 06:17
  • How about making use of the [URL API](https://developer.mozilla.org/en-US/docs/Web/API/URL_API) which already has it all? – Peter Seliger Mar 29 '21 at 06:22
  • https://regexr.com/5pj1t – BOZ Mar 29 '21 at 06:49
  • ... and maybe [`/(?:https*:\/\/)*(?:www\.)*[^.\s\/]+(?:\.[^.\s\/]+)/`versus `/(?:https*:\/\/)*(?:www\.)*[^.\s\/]+(?:\.[^.\s\/]+)+/`](https://regex101.com/r/fI0KLf/1/) for a very rough first plausibility check. – Peter Seliger Mar 29 '21 at 06:49
  • Sorry, you say your regex does not match the URLs you posted, but it [does match them](https://regex101.com/r/dZpWSE/1). So, what is the issue? – Wiktor Stribiżew Mar 29 '21 at 09:29

0 Answers0