5

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?

mikemaccana
  • 110,530
  • 99
  • 389
  • 494

2 Answers2

13

Use required in order to not validate empty input.

<input pattern="[a-z]" required />
mikemaccana
  • 110,530
  • 99
  • 389
  • 494
Konstantin Dinev
  • 34,219
  • 14
  • 75
  • 100
  • 1
    The rationale behind this design decision is, of course, to be able to validate optional fields. – Álvaro González Jun 19 '17 at 15:35
  • You can validate the whole form (which validates all contained inputs) or you can validate fields separately and act accordingly. Both options have advantages/disadvantages – jorgefpastor May 13 '19 at 15:16
1

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.
}
RatherBKnitting
  • 411
  • 3
  • 14