【问题标题】:How to centralize forms validations in React?如何在 React 中集中表单验证?
【发布时间】:2022-06-13 14:47:08
【问题描述】:

我想集中表单验证。我创建了一个文件:src/schemas/schemas.js

在这个文件中,我放置了所有表单验证,例如:

export const schemaRegister = yup.object().shape({
  username: yup.string().required("Username is required").matches(/^[0-9a-z]+$/),
  password: yup.string().required("Password is required").min(8).otherValidations...,
  passwordConfirmation: yup.string()
    .required("Password confirmation is required")
    .oneOf([yup.ref("password"), null], "Passwords must match")
});

export const schemaLogin = yup.object().shape({
  username: yup.string().required("Username is required"),
  password: yup.string().required("Password is required").min(8).otherValidations...,
});

OTHER SCHEMAS

我有两个疑问:

  1. 是否可以将所有表单验证架构放在一个文件 (src/schemas/schemas.js) 中?

  2. 如您所见,在这两种模式中,我都在重复

    password: yup.string().required("Password is required").min(8).otherValidations...
    

有没有办法避免重复代码?因为我有其他表单,有些字段的验证比较复杂,所以就不再赘述了

【问题讨论】:

    标签: javascript reactjs yup


    【解决方案1】:

    您可以避免重复。假设您想在schemaRegister 中使用schemaLogin。您可以像这样使用.shape 合并这些架构:

    const schemaRegister = schemaLogin.shape({
                           passwordConfirmation: yup.string()
                          .required("Password confirmation is required")
                          .oneOf([yup.ref("password"), null], "Passwords must match")
    });
    

    【讨论】:

      猜你喜欢
      • 2021-09-19
      • 2019-02-22
      • 2020-03-16
      • 2020-06-18
      • 1970-01-01
      • 2021-11-15
      • 1970-01-01
      • 2021-05-14
      • 1970-01-01
      相关资源
      最近更新 更多