Joi validate create and update operations with only one schema

Bright Larson Nanevie
2 min readMar 28, 2021

Have you always created two separate schemas just to validate your data for create and update operations? STOP NOW! There’s a better way.

Now, let’s assume, you have a schema that accepts email and password fields. When running a “create” operation, we want “password” to be required, but we don’t want to accept a password field when running “update” operations. Let’s take a dive into how we can do that by defining just one schema.

Joi schema

In the above code, we use Joi.alter method to define a set of alternate options to the schema.

To tell the schema which option we want to use, we call the schema.tailor method and pass the option, which is either “post” or “put” in our case.

Our schema is ready, now let’s use it.

Using validation schema

When we call the validateUser function and pass the “post” argument, we get an error “password is a required field”.

On the other hand, when we pass “put” as a second argument to the validateUser function, The error object is undefined, thus the validation passed.

Hope you enjoyed the read. Catch you another time.

--

--

Bright Larson Nanevie

Full stack developer, NodeJs (express), React, React-native, MongoDB