All Articles

Data validation with Yup

In this article, I will explain why you would use Yup, what it does and how you can get started validating your data with Yup.

Even though Yup is designed to be used in the browser as it is said in their documentations it is possible to use it on the server and if you need something more than a leaner JavaScript object schema validator I would definitely recommend you to check out Joi, but I definitely do not recommend you to use Joi on the browser, let’s get started.

Why would you use Yup at all?

If you have ever done data validation you might have already coded some crazy validation logic as I did… and… well… that is a lot frustrating.

Yup is here to make our lives easier and to simplify this process. It is easy to use and will not affect your business logic at all.

JavaScript frameworks have now evolved in such a way that we now exchange more data than ever before and you want to make sure the data you are sending to an API, showing to the user or storing in the database is correct, otherwise, it might bring you some troubles.

How Yup works?

With Yup you will design an object schema and use Yup’s functions to check if your targeted object matches with the designed object schema.

So first let’s declare which object we are going to validate in this example, let’s validate a user, it can be either for storing in a database on your server or submitting a form on the browser.

const object = {
  name: 'Leo Motta',
  age: 26,
  email: 'mail@mail.com',
}

Now that we have our object, let’s break it into steps.

1. Declare a Yup object schema.

First, Yup does not have a default export, you will either want to destructure it or import everything as default.

import * as Yup from 'yup';

const schema = Yup.object().shape({
  name: Yup.string().required(),
  age: Yup
    .number()
    .required()
    .positive()
    .integer(),
  email: Yup.string().email(),
});

Notice it is not hard to understand, inside shape() we are just declaring an onject and calling Yup validation functions.

  • object: Will define an object schema.
  • object.shape: Define the keys of the object.
  • Yup.string: Specify it as type string.
  • Yup.number: Specify it as type number.
  • Yup.required: Specify it as required field.
  • Yup.positive: Specify it as positive value.
  • integer: Specify it as integer value.
  • email: Specify it to be a valid email format.

2. Validate objects with Yup schema.

Now we want to use our schema to validate our object, but from here we have more than one option, and I would like to demonstrate at least 2 options.

2.1 Validate with isValid()

Reference

Returns true when the passed in value matches the schema. isValid is asynchronous and returns a Promise object and it takes your object as an argument.

// returns true or false
schema.isValid(object); 

2.2 Validate with validate()

Reference

Returns the value if the value is valid, and returns the errors otherwise. This method is asynchronous and returns a Promise object, that is fulfilled with the value, or rejected with a ValidationError.

When using validate there is a great advantage of taking custom error messages and it also takes some options as the second argument. When calling Yup function you can pass a string as an argument and it will be returned as your custom message, see the example below:

const schema = Yup.object().shape({
  name: Yup.string().required('Name is required.'),
  age: Yup
    .number()
    .required('Age is required.')
    .positive('Age most be a positive number.')
    .integer('Age most be an integer.'),
  email: Yup.string().email('Not valid email.'),
});

With your custom messages all set, you can call the validate method and have returned to you just like this:

schema.validate(object).catch(function(err) {
  err.name; // => 'ValidationError'
  err.errors; // => '['some messages']'
  err.inner; // => '[{}]' an array of object with more details
  err.inner[index].path; // => 'object_key' object key that failed
  err.ineer[index].message; // => 'Your custom error message'
});

Now it is up to you to test Yup and fit it to your workflow. I want you to keep in mind that Yup is not just a data validation package it can also parse your objects and it is even possible to write some conditional validations with Yup .when() function, so if you want to make more advanced use of Yup I can only recommend the official documentation here;

Conclusion

Developing custom data validation can be quite complex and Yup makes this task really easy, it will save you a lot time and it works really well, but if you want to validate data on the server it is ok to use Yup but there is also Joi with has some fancy features for data validation, so it depends on your needs.