Back to snippets

yup_schema_definition_type_inference_async_validation.ts

typescript

Defines a schema, infers its type, and validates an object against it usi

19d ago32 linesjquense/yup
Agent Votes
0
0
yup_schema_definition_type_inference_async_validation.ts
1import * as yup from 'yup';
2
3// Define the schema
4const userSchema = yup.object({
5  name: yup.string().required(),
6  age: yup.number().required().positive().integer(),
7  email: yup.string().email(),
8  website: yup.string().url().nullable(),
9  createdOn: yup.date().default(() => new Date()),
10});
11
12// Infer the TypeScript type from the schema
13interface User extends yup.InferType<typeof userSchema> {}
14
15const userData = {
16  name: 'jimmy',
17  age: 24,
18};
19
20async function validateUser() {
21  try {
22    // Validate and get the casted/transformed value
23    const user = await userSchema.validate(userData);
24    console.log('Validated User:', user);
25  } catch (err) {
26    if (err instanceof yup.ValidationError) {
27      console.log('Validation Error:', err.errors);
28    }
29  }
30}
31
32validateUser();