What is form validation?

Form validation is a part of programming forms that ensures that all required fields are filled out according to expectations. This can be as simple as requiring that a field has data, to as complex as ensuring that certain fields have data according to previous other fields having data (think education: If a user graduates college, you want to know what they majored in, but high schoolers merely graduate without a focus).

What can be validated?

There are three main aspects of data that can be validated: That the data exists, it is of a certain type, and that it matches a pattern.

Validating data exists

This is the simplest form of validation. All that is done is ensuring the field is both sent to the backend and isn't just an empty string, null, or blank.

Validating types

It is possible to ensure that data is in one of several types, such as a string/text or a number.

Files can also be validated to ensure they are the proper document type and above or below a certain size.

Validating patterns

This a little misleading, and that's on purpose. Most validation will say it matches a valid format. However, in many cases, that's either overkill or impossible.

For example, take the email address This is a valid email address. However, no email account exists at that address. The pattern can be validated, but not the reality.

The same holds true for things like dates, URLs/web addresses, phone numbers, and alphanumeric account numbers. The pattern can be tested, but not necessarily that it's "correct".

The exception to the rule

If a database exists with the correct data, we can compare against it. However, it is still up to you to ensure that the information provided is correct and up to date.

A live example of this is your ability to login to your website. We compare your username and password against what's saved in the database. However, we can't guarantee that the email address you use is active.

Best Practices

  1. Only require what is absolutely necessary.
    Do you really need their home phone, or just a number where they can be reached?
  2. Don't limit input if possible; let the validation match a pattern and nothing else.
    Phone numbers don't need to be 10 solid digits. It's not only difficult to read, but what if the user has an extension, or is outside the US and needs the country code?
  3. Let the user fail.
    If the user fails to fill something out, what does that say about them?