Dead simple Object schema validation
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
let 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
let 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"
let 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: SchemaMetadata): 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(message?: string | function): SchemaSchema.nonNullable(message?: string | function): 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, schema: Schema, options: object) => 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.datetime(options?: {message?: string | function, allowOffset?: boolean, precision?: number})string.datetime(message?: string | function)string.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): ObjectSchema](#objectconcatschema