So I have an input element in HTML, that input element asks the user for his website's address/name.
Now here's the thing I accept the following address/name formats:
https://example.com
(.net, .org, etc.)http://example.com
(.net, .org, etc.)www.example.com
(.net, .org, etc.)http://www.example.com
(.net, .org, etc.)https://www.example.com
(.net, .org, etc.)example.com
(.net, .org, etc.)
But If the user types a random string for example, abc123$
It would give an error "Please enter a valid website address/name".
What I tried so far,
const isValidURL = (str) => {
var a = document.createElement("a");
a.href = str;
return a.host && a.host != window.location.host;
}
let isValid = isValidURL("https://example.com");
if (isValid == true) {
// pass
} else if ...
Now, this code I found on an SO answer checks to see If it is a valid URL, i.e. contains http or https which is part of what I want. But after this in an else if statement I would also want to allow URLs that don't contain http or https but contain www. and then in another else if statement I would want to allow URLs that contain neither of those and just example.com (.net, .org, etc.), but THEN an else statement which tells the user "Please enter a valid website address/name".
But the problem is that I have no idea how I will do this, I would appreciate it if someone were to shed some light upon this.
Note: I do know that checking the URL on the backend is the best thing to do but sadly due to client requirements I need to use this client-side method of the bare-minimum sitename validation.
Edit: This is not a duplicate of other such questions because I am not just trying to validate the URLs, I am trying to validate all the possible domain name types valid on a web browser. See the examples I presented above, not all of them are valid URLs the ones that aren't should pass too, but If it is not a valid site name entirely like "example" instead of "example.com, www.example.com, or http://example.com, etc." then It doesn't pass.