Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Revisit Yup #156

Open
reboottime opened this issue Sep 1, 2023 · 1 comment
Open

Revisit Yup #156

reboottime opened this issue Sep 1, 2023 · 1 comment

Comments

@reboottime
Copy link
Owner

reboottime commented Sep 1, 2023

What is Yup and its applications

  • Yup is a versatile schema builder designed for runtime value parsing and validation. Its killer features include:
    • composable and Reusable: supports compose bigger schema from smaller schema units
    • Rich error details, make debugging a breeze
  • The application on frontend Dev: It is widely adopted in various form validation solutions, including React Formik, React Hook Form, and Mantine UI Form, etc.
@reboottime
Copy link
Owner Author

reboottime commented Sep 1, 2023

Practices using Yup as form validation solution

  • Derive data type from Yup Schema ( in TypeScript)
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
}*/
  • Add validation error manually via test function
const order = object({
  no: number().required().
  sku: string().test({
    name: 'is-sku',
    skipAbsent: true,
    test(value, ctx) {
      if (!value.startsWith('s-')) {
        return ctx.createError({ message: 'SKU missing correct prefix' })
      }
      if (!value.endsWith('-42a')) {
        return ctx.createError({ message: 'SKU missing correct suffix' })
      }
      if (value.length < 10) {
        return ctx.createError({ message: 'SKU is not the right length' })
      }
      return true
    }
  })
})

order.validate({ no: 1234, sku: 's-1a45-14a' })

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant