mikemaccana
mikemaccana

Reputation: 123490

HTML5 checkValidity says an empty input is valid

Given the following document:

<input pattern="[a-z]"/>

Without filling in the input, running:

document.querySelector('input').checkValidity()

Returns true.

Since an empty input would not match [a-z], why is HTML5 checkValidity() returning true?

Upvotes: 5

Views: 4300

Answers (2)

Konstantin Dinev
Konstantin Dinev

Reputation: 34905

Use required in order to not validate empty input.

<input pattern="[a-z]" required />

Upvotes: 13

RatherBKnitting
RatherBKnitting

Reputation: 421

You can get around having to add required by adding a check that your value is not empty. It's pretty obvious, but I thought I would mention it here because I am not posting this input and adding required forces the user to enter a value, which is not what I need.

if (myCustomJavaScript.notFalsy($input.val()) && $input[0].checkValidity()) {
 // Submit AJAX request.
}

Upvotes: 1

Related Questions