For checking and adding auto http protocol for input type URL validation

In normal input field ‘type = URL’ in the HTML form, has a default validation. It will only allow a URL with prefix protocol. ie, http://www.test.com as a sample domain. Even though www.test.com is a valid domain structure, it will be failed for the above-mentioned validation. It is necessary for http:// or https:// protocol.

So, the below-mentioned functionality will help you to solve the above-mentioned issue.

JS
<script>
                        function checkURL (abc) {
                          var string = abc.value;
                          if (!~string.indexOf("http")) {
                            string = "http://" + string;
                          }
                          abc.value = string;
                          return abc
                        }
</script>

HTML

<input type="url" onblur="checkURL(this)" required>
  • Will check the input field value, whether it contains protocol or not.
  • If not, it will add http:// to the field on submission.

Leave a comment

Your email address will not be published. Required fields are marked *