TOC

The community is working on translating this tutorial into Chinese, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".

Form validation using HTML5:

Validating URLs

If you ask what constitutes a valid URL you will most definitely get different answers depending on who you ask. This affects the url input type and means that even though most browsers demand a URL prefix you can make one up yourself and both http:// and bonk:// will be accepted as valid url prefixes. (Actually, the only thing you need is a letter and the colon - try it out yourself in the LIve Preview Validator below). On the other hand, no spaces are allowed but your url doesn’t need to include a period. As I have hopefully made clear, you cannot rely completely on the url input for validation yet, but it is still a good idea to include it as it future-proofs your website.

<form>
	<input type="url" required />
	<input type="submit" value="Submit Now!">
</form>

Luckily, we can improve the url validation inout type by adding the pattern attribute to our input field.The pattern attribute accepts JavaScript Regular Expressions. If you are not familiar with regular expressions, all you need to know by now, is that you can add the following attribute: pattern="https?://.+" to your input field, and then you have improved your url validation by demanding that all url's start with either http:// or https://

<form>
	<input type="url" pattern="https?://.+" required />
	<input type="submit" value="Submit Now!">
</form>

This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!
adplus-dvertising