Reputation: 24422
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
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
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
https://
if http
or https
isn't already prepended
in the input field valuehttps://
even when there is http
or https
that isn't in the beginninghttps://
if input field has no valueLimitations
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 workPS: 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
Reputation: 5565
One-liner:
<input type="url" onblur="if (!~this.value.indexOf('http')) this.value = 'https://' + this.value">
Upvotes: 2
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
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
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
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>
Upvotes: 26
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
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
}
I hope it will help
Upvotes: 7