5

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.

1
  • 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. No, the value still must fit the URL pattern regardless of additional pattern criteria. Therefore it must start with a protocol. Commented Jun 13, 2019 at 12:44

1 Answer 1

7

Add ? to the pattern

pattern="https?://.*"

? makes s optional.

Sign up to request clarification or add additional context in comments.

1 Comment

I have a similar question. i am wondering if you can have a look.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.