validasaur icon indicating copy to clipboard operation
validasaur copied to clipboard

Added `isUrl()` rule

Open rachids opened this issue 4 years ago • 8 comments

I wasn't able to convert the massive regexp rule from Laravel/Symfony into Validasaur, but this one will make any of the below urls valid :

  • test.com
  • test.com/
  • www.test.com
  • http://www.test.com
  • https://www.test.com

rachids avatar Jul 16 '20 16:07 rachids

Sorry for late reply. I think it is ok to only support http/s scheme for now.

But I test your regex at https://regexr.com/58lpv, it fails in some tests. Could you fix it?

emsifa avatar Jul 18 '20 13:07 emsifa

No problem! I will be out of my home for the next week, i will be sure to complete this when I come back.

rachids avatar Jul 18 '20 16:07 rachids

Does this work for //url.com also?

n10000k avatar Aug 04 '20 20:08 n10000k

@narwy I think this rule shouldn't allow schemeless URL.

Or maybe we can add schemes option to allow schemeless URL. By default, it only allows "http" and "https" schemes. If we want to allow schemeless URL we could put a blank string in schemes.

For example:

isUrl() // valid with URL with http and https schemes
isUrl({schemes: ['http', 'https', 'ftp', '']}) // valid for "//foo.com", "https://foo.bar", "http://foo.com", "ftp://foo.com", etc 

emsifa avatar Aug 05 '20 16:08 emsifa

but then that would defeat the purpose of the naming isUrl I would suggest we add the schemes options for sure

n10000k avatar Aug 05 '20 18:08 n10000k

Hey @rachids , do you able to continue this PR?

If you are able to continue this PR, I would like to add some tests in your code.

emsifa avatar Aug 09 '20 10:08 emsifa

Hello @emsifa, yes I will try to comply to all your regex rules 😉

Edit: I might require some help on achieving the regex rule

rachids avatar Aug 10 '20 13:08 rachids

@emsifa @rachids Why not use the URL object provided to you?

function isUrl(text: string, protocols: string[] = ["https:"]) {
  const url = new URL(text);
  if (!protocols.includes(url.protocol)) {
    throw new Error(
      `Only ${protocols.join(
        ", "
      )} are supported. The url you provied has a protocol of: ${url.protocol}`
    );
  }
  return url;
}

console.log(isUrl("https://url.com"));

You can modify the above example to fit your use case.

searchableguy avatar Mar 19 '21 10:03 searchableguy