Validation with Either
Explore how to implement data validation for user registration using the Either monad from fp-ts. Understand creating functions that enforce mandatory fields, validate specific data like age and sex, and combine checks using functional programming patterns like chain and pipe to handle errors effectively.
We'll cover the following...
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
18or older. In order not to exclude any senior citizens, we’ll set the max limit of age to150.
We’ll also have to change our incoming values into values our User type is expecting. But we’ll start with validation.
- 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