Custom Form Validation

Learn how to do custom form validation and get some practice.

Form validation is fundamental for most web applications. Of course, front-end form validation alone isn’t effective without back-end form validation, but front-end form validation gives the user quick feedback without waiting for the back-end response.

HTML5 form validation

Since the introduction of HTML5, client-side form validation has become simple. Basic client-side form validation doesn’t require JavaScript anymore. In addition, any invalid field will automatically prevent a form submit. We can implement HTML5 validation with up to seven different attributes:

  • required: This is utilized if an element needs a value at all.
  • type: This is a general indicator of the type of data (number, email password, etc.).
  • minlength: This is the minimum length of the input.
  • maxlength: This is the maximum length of the input.
  • min: This is the minimum numeric value of the input.
  • max: This is the maximum numeric value of the input.
  • pattern: This is a regular expression the value is matched against.

Arguably, the most flexible attribute is pattern. Since it uses a regular expression, we can define almost anything as a valid pattern. Most other attributes can even be rebuilt with a pattern.

However, most browsers follow the magic pushbutton anti-pattern. The magic pushbutton describes a single button that triggers all business logic. For example, “Submit” buttons are usually these kinds of magic pushbuttons—validation only ever happens upon submission.

HTML5 form validation isn’t ideal for several reasons:

  1. The magic pushbutton anti-pattern can cause frustration for the user. After fixing a single error, they need to resubmit only to get a notice for the error message that follows.
  2. Error messages are often not ideal. They tell the user that something is wrong but not what exactly is wrong. Think of postal codes, for example.
  3. Error messages cannot be styled or modified.

Custom form validation can mitigate most, if not all, of these drawbacks, more so with Vue.js. Inherited components, v-model, references, and custom events allow us to implement validatable form elements that don’t require more than a few rules and event listeners.

Get hands-on with 1200+ tech skills courses.