Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

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?

like image 393
Ryan Avatar asked Jul 30 '13 12:07

Ryan


People also ask

Is URL valid input field in HTML?

The <input type="url"> defines a field for entering a URL. The input value is automatically validated before the form can be submitted. Tip: Always add the <label> tag for best accessibility practices!

What is a validation URL?

Link validation pings the destination of a URL and tests for errors. This helps avoid broken and invalid links in your published document, and is especially useful for bloggers.

Which HTML5 input type allows the user to select a month and year?

Input Type Month The <input type="month"> allows the user to select a month and year. Depending on browser support, a date picker can show up in the input field.


2 Answers

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

like image 150
ginna Avatar answered Oct 05 '22 22:10

ginna


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 ;)

like image 27
dove Avatar answered Oct 05 '22 22:10

dove