Ryan
Ryan

Reputation: 24422

With HTML5 url input validation assume url starts with http://

HTML5 provides for automatic URL validation :-

<form>
   <input type="url" name="someUrl">
</form>

This will fail validation for URL's that don't have a protocol prefix - e.g. stackoverflow.com will fail while http://stackoverflow.com will pass.

How can I automatically add http:// to a url if there isn't already a protocol?

I could add a onblur event handler but is there a better way like some before validation event?

Upvotes: 35

Views: 32183

Answers (9)

Lars
Lars

Reputation: 89

Using the URL class would be even better.

    function validateUrl(value) {
        try {
            const currentUrl = new URL(value);
            const { protocol } = currentUrl;

            if (protocol !== 'http:' && protocol !== 'https:') {
                currentUrl.protocol = 'http:';
                return currentUrl.toString();
            }
        } catch(e) {
            return `http://${value}`;
        }
    }

The advantage here is that you check for any protocol first. In case the user mistyped the protocol (e.g. htts:), it will be replaced by http:. The answers above would all prepend a new protocol which would result in something like http://htts:. In case there is no protocol it will just prepend http:// in the catch block.

Upvotes: 4

arafatgazi
arafatgazi

Reputation: 429

It will help users with http prepending annoyance without being intrusive. Just add this JavaScript code to your webpages with type="url" <input> elements, and everything will work automatically.

// Run a callback function after DOM is fully loaded
function domReady(callback) {
    if (document.readyState != "loading") {
        callback();
    } else {
        document.addEventListener("DOMContentLoaded", callback);
    }
}

// Prepend https to url input field value if already not prepended by http or https
domReady(() => {
    const urlInput = document.querySelectorAll('input[type="url"]');
    for(i = 0; i < urlInput.length; i++) {
        urlInput[i].addEventListener('change', function(){
            let urlValue = this.value;
            // If http or https isn't prepended as case insensitive characters and if the input field has any value
            if (!urlValue.match(/^https?:/i) && urlValue.length) {
                urlValue = "https://" + urlValue;
                this.value = urlValue;
            }
        });
    }
});

Advantages

  1. prepending https:// if http or https isn't already prepended in the input field value
  2. prepending https:// even when there is http or https that isn't in the beginning
  3. automatically modifying value after users leave input field
  4. not adding https:// if input field has no value
  5. working in a case insensitive manner
  6. automatically working on all url type input fields without requiring to modify HTML input field elements

Limitations

  1. adding https:// in front of valid urls that start with any schemes other than http or https such as ftp and tel which will cause those valid URLs to not work

PS: If you also want to change http to https, append this else if statement to the last if statement in the previous code.

else if (urlValue.match(/^http:/i)) {
    urlValue = urlValue.replace(/^http:/i, "https:");
    this.value = urlValue;
}

Upvotes: 3

Grzegorz Adam Kowalski
Grzegorz Adam Kowalski

Reputation: 5565

One-liner:

<input type="url" onblur="if (!~this.value.indexOf('http')) this.value = 'https://' + this.value">

Upvotes: 2

Toskan
Toskan

Reputation: 14931

what you guys probably want to use is this:

$(function(){
         $('input[type="url"]').on('blur', function(){
           var string = $(this).val();
           if (!string.match(/^https?:/) && string.length) {
             string = "https://" + string;
              $(this).val(string)
           }
         });
});

this runs on document ready

checks if value is empty or has missing http at the beginning

inserts it in that case on blur

thanks @1j01

Upvotes: 9

Carter Medlin
Carter Medlin

Reputation: 12465

This will prepend the URL before submitted if it does not have a http or https in the URL. It is also case insensitive (the i at the end). I'm also using onchange instead of the other events to account for users pressing the enter key and submitting the form that way.

SCRIPT:

function checkURL(o) {
    if (!/^https?:\/\//i.test(o.value)) {
        o.value = "http://" + o.value;
    }
}

ALTERNATE SCRIPT: (Always correct to "http://")

function checkURL(o) {
    o.value = o.value.replace(/^(https?:\/\/)?/i, "http://");
}

HTML:

<form>
   <input type="url" name="someUrl" onchange="checkURL(this)" >
</form>

Upvotes: 1

Vladimir Vovk
Vladimir Vovk

Reputation: 798

You can try to force users enter valid url by providing initial value and placeholder.

<label for="some-url">Some url:</label>
<input id="some-url" type="url" placeholder="http://example.com" value="http://">

Upvotes: 6

ginna
ginna

Reputation: 1801

The code for this should not interrupt the user's action, but should instead wait until the user leaves the form field to check the input text for "http". So use "onblur" instead of "onkeyup".

Then, just see if the string contains "http" using indexOf. If not, it will return -1, which is falsey.

function checkURL (abc) {
  var string = abc.value;
  if (!~string.indexOf("http")) {
    string = "http://" + string;
  }
  abc.value = string;
  return abc
}
<form>
  <input type="url" name="someUrl" onblur="checkURL(this)" />
  <input type="text"/>
</form>

Fiddle

Upvotes: 26

dove
dove

Reputation: 20674

if you don't want the browser validation (it can vary between browsers) you can add the following novalidate attribute

<input type="url" name="someUrl"  formnovalidate="formnovalidate"> 

else you might want to be more transparent about prefixing http:// by simply adding once someone starts to type or even to have http:// already typed into the box on the page load

(credit to editor who rightly points out that novalidate applies to form, while above overrides that, debit to creditor for approach to edit ;)

Upvotes: 10

Sonu Sindhu
Sonu Sindhu

Reputation: 1792

you can use

HTML :

<form>
   <input type="url" name="someUrl" onkeyup="checkUR(this)" >
</form>

SCRIPT:

function checkUR(abc){
    string = abc.value
    if(!(/^http:\/\//.test(string))){
        string = "http://" + string;
    }
    abc.value=string
}

example

I hope it will help

Upvotes: 7

Related Questions