1

URL validation checks if a given text is a URL or not. Such checks are often performed when a user has to enter a URL on a web form. To ensure that the entered text corresponds to a URL, I tried to implement the regex like this

regexurl = “((http|https)://)(www.)?” + “[a-zA-Z0-9@:%._\\+~#?&//=]{2,256}\\.[a-z]” + “{2,6}\\b([-a-zA-Z0-9@:%._\\+~#?&//=]*)”

But I am getting error, Please help where I am being wrong Thanks in advance

Rifky Niyas
  • 1,737
  • 10
  • 25
Megha Arora
  • 21
  • 1
  • 9

1 Answers1

2

If your runtime supports it, the better way of validating URLs is using the URL constructor. You can then use the parsed object to verify parts of it separately. For example, to check if something is a valid HTTP(s) URL:

function isValidHttpUrl(s) {
  let url;
  try {
    url = new URL(s);
  } catch (e) { return false; }
  return /https?/.test(url.protocol);
}

isValidHttpUrl("banana"); // false, not a URL
isValidHttpUrl("http://example.com"); // true, is an HTTP URL
isValidHttpUrl("ftp://example.com"); // false, wrong protocol
gustafc
  • 28,465
  • 7
  • 73
  • 99
  • It's not reliable. a string like 'https:fgnfxn gf.com.comsfgfgfsag' passed the validation (with a space & no slashes after the protocol – nickornotto Aug 30 '22 at 13:39
  • @nickornotto `isValidHttpUrl('https:fgnfxn gf.com.comsfgfgfsag')` returns false for me, what platform are you on? – gustafc Sep 02 '22 at 08:20
  • This is what I get: Error: URL.protocol is not implemented – bieboebap Nov 23 '22 at 16:02
  • 1
    @bieboebap You don't mention what platform you're using, but it's probably a bit old, looking at https://developer.mozilla.org/en-US/docs/Web/API/URL#browser_compatibility we can see that `URL.protocol` has been implemented since 2016 for all runtimes they list. If you can't bump it (and don't find a suitable polyfill), this solution will sadly not work. Have you tried googling the error message? I get several hits which may be relevant to you (for example `react-native-url-polyfill`). – gustafc Nov 24 '22 at 09:49
  • yeah thanks, I found the 3th party libraries (like react-native-url-polyfill), but I did a workaround rather than try it out. – bieboebap Nov 24 '22 at 22:15