Yup reference
2 November 2022 (Updated 26 October 2023)
On this page
What is Yup?
Yup is a JavaScript schema builder library that lets you define a schema and then:
- Transform values to match the schema (using cast()).
- Validate the shape of a value against the schema (using
validate()
).
Yup separates the transformation and validation functions into two separate steps. But you can perform both functions together (e.g., in HTML form validation) or separately (e.g., when deserializing API data).
Basic usage
import * as yup from 'yup';
let schema = yup.object().shape({
name: yup.string().required(),
age: yup.number().required().positive().integer(),
email: yup.string().email(),
website: yup.string().url(),
createdOn: yup.date().default(function () {
return new Date();
}),
});
// check validity
schema
.isValid({
name: 'jimmy',
age: 24,
})
.then(function (valid) {
valid; // => true
});
// you can try and type cast objects to the defined schema
schema.cast({
name: 'jimmy',
age: '24',
createdOn: '2014-09-23T19:25:25Z',
});
// => { name: 'jimmy', age: 24, createdOn: Date }
cast()
Signature:
mixed.cast(value: any, options = {}): any
This will attempt to cast the passed in value
to a value that matches the schema. For example, '5'
will be cast to 5
if using the number()
type. Failed casts typically return null
, but can also return results like NaN
or unexpected strings.
validate()
Signature:
mixed.validate(value: any, options?: object): Promise<any, ValidationError>
This is a asynchronous function that will return a different value depending on if validation passed or not:
- Validation passed: Returns the value.
- Validation failed: Returns
ValidationError
.
Example usage:
schema.validate({ name: 'jimmy', age: 24 }).then(function (value) {
value; // => { name: 'jimmy',age: 24 }
});
schema.validate({ name: 'jimmy', age: 'hi' }).catch(function (err) {
err.name; // => 'ValidationError'
err.errors; // => ['age must be a number']
});
Sources
Tagged:
Yup
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment