Reputation: 71
I want to make a custom validator that should check the input Url is valid or not.
I want to use the following regex that I tested in expresso, but comes off invalid when used in typescript (the compiler fails to parse it):
(((ht|f)tp(s?))\://)?((([a-zA-Z0-9_\-]{2,}\.)+[a-zA-Z]{2,})|((?:(?:25[0-5]|2[0-4]\d|[01]\d\d|\d?\d)(?(\.?\d)\.)){4}))(:[a-zA-Z0-9]+)?(/[a-zA-Z0-9\-\._\?\,\'/\\\+&%\$#\=~]*)?
The above url checks for optional http:\\\
and also will validate an Ip address
The following url's should be valid :
The following url's should be invalid:
Kindly assist
Upvotes: 1
Views: 8214
Reputation: 748
There may be another option for you, that relies on the URL
class. The idea is to try converting the string into a URL
object. If that fails, the string does not contain a valid URL.
public isAValidUrl(value: string): boolean {
try {
const url = new URL(value);
return isValid(url.pathname);
} catch (TypeError) {
return false;
}
}
isValid(value: URL): boolean {
// you may do further tests here, e.g. by checking url.pathname
// for certain patterns
}
Alternatively to returning a boolean you may return the created URL or null instead of a boolean or - if that exists in JavaScript or TypeScript: something like an Optional<URL>
. You should adapt the method's name then, of course.
Upvotes: 1
Reputation: 29824
The forward slashes /
are not escaped in the regex.
What is valid or invalid in Javascript is valid or invalid in Typescript and vice-versa.
Upvotes: 1