Validation with Either

Learn about functions that check the validity of data.

We'll cover the following...

Overview

Now we have types for our incoming data and users. Let’s think about the functions we need, mainly focused on validation. We need functions that:

  • Ensure we have no empty or missing values. Everything is mandatory for us.
  • Check whether we received valid input for a user’s sex.
  • Check the validity of age, as we want our users to be 18 or older. In order not to exclude any senior citizens, we’ll set the max limit of age to 150.

We’ll also have to change our incoming values into values our User type is expecting. But we’ll start with validation.

Press + to interact
import * as E from 'fp-ts/lib/Either';
export type FieldsNotEmpty = (e: UserRegistrationDto)
=> E.Either<string, UserRegistrationDto>;
export type ValidateAge = FieldsNotEmpty;
export type ValidateGender = FieldsNotEmpty;
  • Line 1: We don’t need this style of importing for this particular example. But it becomes handy when we use more than one monad in a file because of an overlap in names (all monads have a map, chain, and so on).
  • Lines 5–6: Since the signature of these two functions is the same as the
...