I have a regex for validating IP addresses and domain names which has been working well so far
/** Checks if a URL is valid */
export function isValidURL(str: string): boolean {
var pattern = new RegExp(
'^(https?:\\/\\/)?' + // protocol
'((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' + // domain name
'((\\d{1,3}\\.){3}\\d{1,3}))' + // OR ip (v4) address
'(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*' + // port and path
'(\\?[;&a-z\\d%_.~+=-]*)?' + // query string
'(\\#[-a-z\\d_]*)?$',
'i'
); // fragment locator
return !!pattern.test(str);
}
The problem is when I use a username and password it breaks.
http://admin:admin@192.168.92.106:5500/api/v1/
Is there a solution that would pass the URL as valid if including a username and password in the URL?
You'd just need to add a new line for the user/pass pattern after your "protocol" pattern. What are the requirements for usernames and passwords?
A simple one would looks something like this (assumes usernames are only letters & numbers):
(\w+?:.+@)?
The answer with help from @ejkeep
/** Checks if a URL is valid */
export function isValidURL(str: string): boolean {
var pattern = new RegExp(
'^(https?:\\/\\/)?' + // protocol
'(\\w+?:.+@)?' + // username and password
'((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' + // domain name
'((\\d{1,3}\\.){3}\\d{1,3}))' + // OR ip (v4) address
'(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*' + // port and path
'(\\?[;&a-z\\d%_.~+=-]*)?' + // query string
'(\\#[-a-z\\d_]*)?$',
'i'
); // fragment locator
return !!pattern.test(str);
}