An Introduction to Validation in React with Yup

The JavaScript Object Schema Validator and Object Parser to use with React

Why should you care about Yup?

The general gist of Yup

A Schema Object

{ 
email_address: email <required>
full_name: string, <required>
house_no: int,
address_1: string <required>,
address_2: string,
post_code: string <required>
timestamp: date <required>
}
const checkoutAddressSchema = yup.object().shape({  email_address: yup
.string()
.email()
.required(),
full_name: yup
.string()
.required(),
house_no: yup
.number()
.required()
.positive()
.integer(),
address_1: yup
.string()
.required(),
address_2: yup
.string(),
post_code: yup
.string()
.required(),
timestamp: yup
.date()
.default(() => (new Date()),
}),
});
 ...
timestamp: yup
.date()
.default(() => (new Date()),
}
...
...
timestamp: yup
.date()
.default(() => {
//check for stuff
return new Date();
}),
}
...

Validating Objects with My Schema

let addressFormData = {
email_address: 'ross@jkrbinvestments.com',
full_name: 'Ross Bulat',
house_no: null,
address_1: 'My Street Name',
post_code: 'AB01 0AB',
}

Checking if the object is valid

const valid = await checkoutAddressSchema.isValid(addressFormData);
checkoutAddressSchema
.isValid(addressFormData)
.then(function(valid) {

//valid - true or false
});

Validating the Object

await checkoutAddressSchema.validate(addressFormData);

Casting an Object

checkoutAddressSchema.cast(addressFormData);

Indispensable Tool?

Miscellaneous Useful Methods

await checkoutAddressSchema.validate(addressFormData, { abortEarly: false })

Installing Yup in React Projects

npm i yup

Importing Yup

import * as yup from 'yup';
import { string, required } from 'yup';

Where to go from here

Programmer and Author. Director @ JKRBInvestments.com. Creator of LearnChineseGrammar.com for iOS.

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store