If you keep ’em dumb, you keep it simple

Form validations can be incredibly complicated, but they really shouldn’t. I’ve seen many hours wasted trying to hack 3rd party form validation libraries to fit changing customer requirements. I’ve also seen in-house solutions turn into verbose monstrosities.

Let’s avoid unneeded complexity by building the simplest form validations possible.

Our example form will validate the presence of username and email in this sign-up wizard:

TL;DR here’s the form with working validations

In React, our form component looks like this:

Clicking the submit button triggers the _validate method, which will validate the whole form and generate any necessary error messages. Let’s check for the simple presence of any values within those fields. If either the username or email field is empty, we’ll provide a custom message.

Here is the validate method filled out. We check username and email and mutate the errorMessage object based on what’s in there.

An array of different error messages for each input field is a very handy thing, since there are situations where more than one validation message is required (i.e. password security rules).

Now we just need to display those errors on the form, which can be as simple as using the join operator:

Here’s what the whole thing looks like:

That’s it! Told you this were really simple validations. To run the validations when the input changes, simply combine the _onChange and _validate functions.

This basic pattern covers 99% of form validation needs and is quick and easy to write yourself. Here’s a working JSFiddle example.