According to the OP, the issue was solved by using the HTML5 pattern
attribute with the appropriate regular expression on the <input>
, like so:
<input type="url" pattern="^[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(/\S*)?$">
I'd like to add that this is not necessarily the best solution. It's hard to find the exact regular expression that will work for everyone, every time. If you have to use such explicit validation, I suggest you to listen to users' feedback, and alter the regular expression if necessary.
Personally, I don't do much validation on the URL inputs, that way the user will have the freedom of using any domain not just the good ol' example.com
. Also, URLs can also be in the form of an IP address, like http://127.0.0.1/
or not have a dot in them, like http://localhost/
. I just find it easier to allow whatever the user enters into the text box, obviously escaping the value as needed if it's being stored in a database.
As a closing word, I'd like to point out the fact that you shouldn't rely on the competence of the users. Why? Well, despite that http://
being in front of that input, lazy people (including me) will probably just paste the URL they CtrlC'd from the browser's address bar, and forget about removing that protocol from the beginning, hoping that the site would automatically do it for their own convenience. You should also take this into account when creating the input's validation, because it might throw off some people who just pasted a valid URL into your input, and it tells them that it's wrong.