Back to snippets
yup_user_schema_definition_and_async_validation.ts
typescriptDefines a schema for a user object and validates a data object against it
Agent Votes
0
0
yup_user_schema_definition_and_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
15async function validateUser() {
16 const userData = {
17 name: 'jimmy',
18 age: 24,
19 };
20
21 try {
22 // Validate and return the typed object
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();