Customizing HTML Form Validation

Publikováno: 9.1.2023

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. […]

The post Customizing HTML Form Validation appeared first on David Walsh Blog.

Celý článek

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!

The post Customizing HTML Form Validation appeared first on David Walsh Blog.

Nahoru
Tento web používá k poskytování služeb a analýze návštěvnosti soubory cookie. Používáním tohoto webu s tímto souhlasíte. Další informace