puoygae
puoygae

Reputation: 573

Using <input type="url"> to handle both HTTP and HTTPS

The URL input <input type="url"> takes pattern attribute which allows us to specify a JavaScript regex to validate the input value.

In this MDN example, the pattern provided is pattern="https://.*" which expects an https protocol. This means a http value will not be accepted.

<label for="url">Enter an https:// URL:</label>

<input type="url" name="url" id="url"
       placeholder="https://example.com"
       pattern="https://.*" size="30"
       required>

Not all URLs are HTTPS, so is this option too strict?

In the documentation explaining the pattern attribute, it says:

If the specified pattern is not specified or is invalid, no regular expression is applied and this attribute is ignored completely.

I thought this meant that if the pattern attribute is not included, then the value of www.example.com would be accepted. However, it seems like this is not the case.

Question: How do we use the url input to flexible handle both http and https values? Moreover, it seems like it would be simpler if the user is able to simple enter www.example.com without specifying the protocol.

Upvotes: 5

Views: 4065

Answers (1)

TitanFighter
TitanFighter

Reputation: 5074

Add ? to the pattern

pattern="https?://.*"

? makes s optional.

Upvotes: 7

Related Questions