Yup is a schema builder for runtime value parsing and validation. Define a schema, transform a value to match, assert the shape of an existing value, or both. Yup schema are extremely expressive and allow modeling complex, interdependent validations, or value transformation.
You are viewing docs for the v1.0.0 of yup, pre-v1 docs are available: here
Killer Features:
Schema are comprised of parsing actions (transforms) as well as assertions (tests) about the input value. Validate an input value to parse it and run the configured set of assertions. Chain together methods to build a schema.
import { object, string, number, date, InferType } from 'yup';
let userSchema = object({
name: string().required(),
age: number().required().positive().integer(),
email: string().email(),
website: string().url().nullable(),
createdOn: date().default(() => new Date()),
});
// parse and assert validity
const user = await userSchema.validate(await fetchUser());
type User = InferType<typeof userSchema>;
/* {
name: string;
age: number;
email?: string | undefined
website?: string | null | undefined
createdOn: Date
}*/
Use a schema to coerce or "cast" an input value into the correct type, and optionally transform that value into more concrete and specific values, without making further assertions.
// Attempts to coerce values to the correct type
const parsedUser = userSchema.cast({
name: 'jimmy',
age: '24',
createdOn: '2014-09-23T19:25:25Z',
});
// ✅ { name: 'jimmy', age: 24, createdOn: Date }
Know that your input value is already parsed? You can "strictly" validate an input, and avoid the overhead of running parsing logic.
// ❌ ValidationError "age is not a number"
const parsedUser = await userSchema.validate(
{
name: 'jimmy',
age: '24',
},
{ strict: true },
);
yupreach(schema: Schema, path: string, value?: object, context?: object): SchemaaddMethod(schemaType: Schema, name: string, method: ()=> Schema): voidref(path: string, options: { contextPrefix: string }): Reflazy((value: any) => Schema): LazyValidationError(errors: string | Array<string>, value: any, path: string)SchemaSchema.clone(): SchemaSchema.label(label: string): SchemaSchema.meta(metadata: object): SchemaSchema.describe(options?: ResolveOptions): SchemaDescriptionSchema.concat(schema: Schema): SchemaSchema.validate(value: any, options?: object): Promise<InferType<Schema>, ValidationError>Schema.validateSync(value: any, options?: object): InferType<Schema>Schema.validateAt(path: string, value: any, options?: object): Promise<InferType<Schema>, ValidationError>Schema.validateSyncAt(path: string, value: any, options?: object): InferType<Schema>Schema.isValid(value: any, options?: object): Promise<boolean>Schema.isValidSync(value: any, options?: object): booleanSchema.cast(value: any, options = {}): InferType<Schema>Schema.isType(value: any): value is InferType<Schema>Schema.strict(enabled: boolean = false): SchemaSchema.strip(enabled: boolean = true): SchemaSchema.withMutation(builder: (current: Schema) => void): voidSchema.default(value: any): SchemaSchema.getDefault(options?: object): AnySchema.nullable(): SchemaSchema.nonNullable(): SchemaSchema.defined(): SchemaSchema.optional(): SchemaSchema.required(message?: string | function): SchemaSchema.notRequired(): SchemaSchema.typeError(message: string): SchemaSchema.oneOf(arrayOfValues: Array<any>, message?: string | function): Schema Alias: equalsSchema.notOneOf(arrayOfValues: Array<any>, message?: string | function)Schema.when(keys: string | string[], builder: object | (values: any[], schema) => Schema): SchemaSchema.test(name: string, message: string | function | any, test: function): SchemaSchema.test(options: object): SchemaSchema.transform((currentValue: any, originalValue: any) => any): Schemastring.required(message?: string | function): Schemastring.length(limit: number | Ref, message?: string | function): Schemastring.min(limit: number | Ref, message?: string | function): Schemastring.max(limit: number | Ref, message?: string | function): Schemastring.matches(regex: Regex, message?: string | function): Schemastring.matches(regex: Regex, options: { message: string, excludeEmptyString: bool }): Schemastring.email(message?: string | function): Schemastring.url(message?: string | function): Schemastring.uuid(message?: string | function): Schemastring.ensure(): Schemastring.trim(message?: string | function): Schemastring.lowercase(message?: string | function): Schemastring.uppercase(message?: string | function): Schemanumber.min(limit: number | Ref, message?: string | function): Schemanumber.max(limit: number | Ref, message?: string | function): Schemanumber.lessThan(max: number | Ref, message?: string | function): Schemanumber.moreThan(min: number | Ref, message?: string | function): Schemanumber.positive(message?: string | function): Schemanumber.negative(message?: string | function): Schemanumber.integer(message?: string | function): Schemanumber.truncate(): Schemanumber.round(type: 'floor' | 'ceil' | 'trunc' | 'round' = 'round'): Schemaarray.of(type: Schema): thisarray.json(): thisarray.length(length: number | Ref, message?: string | function): thisarray.min(limit: number | Ref, message?: string | function): thisarray.max(limit: number | Ref, message?: string | function): thisarray.ensure(): thisarray.compact(rejector: (value) => boolean): Schemaobject.shape(fields: object, noSortEdges?: Array<[string, string]>): Schemaobject.json(): thisobject.concat(schemaB: ObjectSchema): ObjectSchemaobject.pick(keys: string[]): Schemaobject.omit(keys: string[]): Schemaobject.from(fromKey: string, toKey: string, alias: boolean = false): thisobject.noUnknown(onlyKnownKeys: boolean = true, message?: string | function): Schemaobject.camelCase(): Schemaobject.constantCase(): SchemaSchema definitions, are comprised of parsing "transforms" which manipulate inputs into the desired shape and type, "tests", which make assertions over parsed data. Schema also store a bunch of "metadata", details about the schema itself, which can be used to improve error messages, build tools that dynamically consume schema, or serialize schema into another format.
In order to be maximally flexible yup allows running both parsing and assertions separately to match specific needs
Each built-in type implements basic type parsing, which comes in handy when parsing serialized data, such as JSON. Additionally types implement type specific transforms that can be enabled.
const num = number().cast('1'); // 1
const obj = object({
firstName: string().lowercase().trim(),
})
.camelCase()
.cast('{"first_name": "jAnE "}'); // { firstName: 'jane' }
Custom transforms can be added
const reversedString = string()
.transform((currentValue) => currentValue.split('').reverse().join(''))
.cast('dlrow olleh'); // "hello world"
Transforms form a "pipeline", where the value of a previous transform is piped into the next one.
If the end value is undefined yup will apply the schema default if it's configured.
Watch out! values are not guaranteed to be valid types in transform functions. Previous transforms may have failed. For example a number transform may be receive the input value,
NaN, or a number.
Yup has robust support for assertions, or "tests", over input values. Tests assert that inputs conform to some criteria. Tests are distinct from transforms, in that they do not change or alter the input (or its type) and are usual