Using Validate.js via a fluent TypeScript interface

When it comes to user input validation, particularly when designing (RESTful, GraphQL) APIs, it’s important to have these objectives in mind:

  • Validator needs to support various data types such as emails, mobile phone numbers in different locales, credit cards, etc. Well tested and already used in production by many companies.
  • It needs to have an API (interface) that allows writing validation rules with the minimum amount of boilerplate code.
  • This interface needs to be strongly typed, allowing a better development experience (DX) when used with TypeScript.

I think validator.js (✭17k) fits perfectly into the first requirement. And, in order to make it less verbose, I would suggest using the following API (interface):

import { validate } from "validator-fluent";

Validation Only (mode)

Often, it also needs to be possible to validate user input without saving it into the database. Example:

const input = {
email: "john@example.com"
};

Adding Custom Rules

You can extend the built-in validator class with any additional validation rules (methods).

import { Validator } from "validator-fluent";

References

Bringing the technical edge to early-stage companies with advice on software architecture, best practices, database design, web infrastructure, and DevOps.