validasaur
validasaur copied to clipboard
Added `isUrl()` rule
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
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?
No problem! I will be out of my home for the next week, i will be sure to complete this when I come back.
Does this work for //url.com
also?
@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
but then that would defeat the purpose of the naming isUrl
I would suggest we add the schemes options for sure
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.
Hello @emsifa, yes I will try to comply to all your regex rules 😉
Edit: I might require some help on achieving the regex rule
@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.