z The Flat Field Z
[ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ]

Schema Validators

Most back end services will accept input by way of JSON. After verifying that the JSON is well formed there is a large amount of validation that will need to performed such as:

A class of libraries called schema validators solve this problem in an elegant and declarative way.

Example API

Let's imagine that we have a database table called dogs with a column called name that is of type VARCHAR(256) NOT NULL. If you were to design a JSON payload to create a dog it might look like:

{
  "name": "Hercules"
}

If our API accepted this payload we would want to check the following:

  • The JSON is well formed.
  • The JSON has a property called name
  • The name property is a string
  • name is at least one char
  • name is not more than 256 chars

Manual Validation

We could do this validation by hand:

function validate(input: string) {
  const json = JSON.parse(input);

  if (
    !(
      json.hasOwnProperty("name") &&
      typeof json.name === "string" &&
      json.name.length > 0 &&
      json.name.length <= 256
    )
  ) {
    throw new Error("Invalid input");
  }
}

This works but it's a lot a of boilerplate. You would also want to return better errors so the caller knew what they needed to fix, which would add even more boilerplate.

Schema Validation

And here is how this would look with schema validation:

const Dog = z.object({
  name: z.string().min(1).max(256),
});

That example uses the excellent Zod. We are doing the same checks but the boilerplate is gone, and what remains is a clear declaration of what we expect the input to look like. Some other perks include:

  • For TypeScript you can infer the type from the schema
  • You will get detailed errors with user actionable messages

Schema validation libraries are in widespread usage and there is probably one for whatever language you work in. Even lower level languages like Go have them.

Tips

Here are some tips for using these libraries effectively:

  • Don't make any calls over the network as part validation
  • Do the validation just after authentication, but before anything else

Conclusion

Schema validation libraries will save you boilerplate, and make your code clearer and more declarative.