DEV Community

George Jempty
George Jempty

Posted on • Edited on

Form Validation, You're Doing it Wrong, Part Two

This is a follow-on to yesterday's post of mine. Again I will be referring to the same excellent article on the sorry state of form validation, though I do have a quibble with the following assertion:

The validity of each field input should be checked when the user leaves the field or reaches the intended input length.

Actually I think their more general position a bit above this is the better guideline:

The validity of the input should not be checked until the user has had a chance to fully type a valid input."

Here the emphasis is mine; I think whether an input is valid can sometimes be determined before "the user leaves the field or reaches the intended input length." To that end I've created another gist, this one demonstrating validating a zip code with an optional dash plus four digits (zip-plus-four) both while the user types, and when they move away from the field.

Specifically I use two slightly different "regular expressions" to achieve this, the one for matching as the user types permitting zero to five beginning digits with an optional dash and then zero to four digits, the one for matching when the user leaves the field requiring precisely five beginning digits, and then an optional dash and precisely four digits -- the actual input as it will be needed for submission in the long run:

  const keyupRegex = new RegExp("^\\d{0,5}(-\\d{0,4})?$");
  const blurRegex = new RegExp("^\\d{5}(-\\d{4})?$"); 
Enter fullscreen mode Exit fullscreen mode

Here is a screenshot showing that the user can type a partially correct entry without getting nagged:

But if they blur off the zip field by clicking the checkbox....

Then though, if the user re-enters the zip field and starts typing something that could potentially be valid (another digit), the error message goes away!

Finally if they finish entering a valid input and uncheck the checkbox, likewise the error is lacking, as it should be.

This technique could likewise be used for email addresses though the regular expressions will be more complicated. Hope you learned as much as I did!

Top comments (0)