Customizing HTML Form Validation

By  on  

Form validation has always been my least favorite part of web development. You need to duplicate validation on both client and server sides, handle loads of events, and worry about form element styling. To aid form validation, the HTML spec added some new form attributes like required and pattern to act as very basic validation. Did you know, however, that you can control native form validation using JavaScript?

validity

Each form element (input, for example) provides a validity property which represents a ValidityState. ValidityState looks something like this:

// input.validity
{
  badInput: false,
  customError: true,
  patternMismatch: false,
  rangeOverflow: false,
  rangeUnderflow: false,
  stepMismatch: false,
  tooLong: false,
  tooShort: false,
  typeMismatch: false,
  valid: false,
  valueMissing: true
}

Each property in the ValidityState can roughly match a specific validation issue: valueMissing would match the required attribute, tooLong and tooShort match minLength and maxLength, etc.

Checking Validity and Setting a Custom Validation Message

Each form field provides a default error message for each error type, but setting a more custom message per your application is likely better. You can use the form field's setCustomValidity to create your own message:

// Check validity
input.checkValidity();

if(input.validity.valueMissing) {
  input.setCustomValidity('This is required, bro!  How did you forget?');
} else {
  // Clear any previous error
  input.setCustomValidity('');
}

Simply setting the message by setCustomValidity doesn't show the message, however.

reportValidity

To get the error to display to the user, use the form element's reportValidity method:

// Show the error!
input.reportValidity();

The error tooltip will immediately display on the screen. The following example displays the error every five seconds:

See the Pen Untitled by David Walsh (@darkwing) on CodePen.

Having hooks into the native form validation system is so valuable and I wish developers used it more. Every website has its own client side validation styling, event handling, etc. Let's use what we've been provided!

Recent Features

  • By
    Create a CSS Cube

    CSS cubes really showcase what CSS has become over the years, evolving from simple color and dimension directives to a language capable of creating deep, creative visuals.  Add animation and you've got something really neat.  Unfortunately each CSS cube tutorial I've read is a bit...

  • By
    From Webcam to Animated GIF: the Secret Behind chat.meatspac.es!

    My team mate Edna Piranha is not only an awesome hacker; she's also a fantastic philosopher! Communication and online interactions is a subject that has kept her mind busy for a long time, and it has also resulted in a bunch of interesting experimental projects...

Incredible Demos

  • By
    CSS Counters

    Counters.  They were a staple of the Geocities / early web scene that many of us "older" developers grew up with;  a feature then, the butt of web jokes now.  CSS has implemented its own type of counter, one more sane and straight-forward than the ole...

  • By
    Telephone Link Protocol

    We've always been able to create links with protocols other than the usual HTTP, like mailto, skype, irc ,and more;  they're an excellent convenience to visitors.  With mobile phone browsers having become infinitely more usable, we can now extend that convenience to phone numbers: The tel...

Discussion

    Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!