Создать динамическую схему проверки Yup из JSON - PullRequest
1 голос
/ 23 июня 2019

Я пытаюсь использовать Yup вместе с Formik в моей форме реакции. Поля формы будут динамическими, так же как и их проверки.

export const formData = [
  {
    id: "name",
    label: "Full name",
    placeholder: "Enter full name",
    type: "text",
    required: true,
    value: "User name",
    values: [],
    validations: [
      {
        type: "minLength",
        value: "5",
        error_message: "name should be atleast 5 char long"
      },
      {
        type: "maxLength",
        value: "10",
        error_message: "name should be atleast 5 char long"
      }
    ]
  },
  {
    id: "email",
    label: "Email",
    placeholder: "Email",
    type: "text",
    required: true,
    value: "email",
    values: [],
    validations: [
      {
        type: "minLength",
        value: "5",
        error_message: "name should be atleast 5 char long"
      },
      {
        type: "maxLength",
        value: "10",
        error_message: "name should be atleast 5 char long"
      },
      {
        type: "email",
        error_message: "Valid email"
      }
    ]
  },
  {
    id: "phoneNumber",
    label: "phone number",
    type: "text",
    required: true,
    value: "7878787878",
    values: [],
    validations: [
      {
        type: "minLength",
        value: "5",
        error_message: "name should be atleast 5 char long"
      },
      {
        type: "maxLength",
        value: "10",
        error_message: "name should be atleast 5 char long"
      },
      {
        type: "required",
        error_message: "phone number is required"
      }
    ]
  },
  {
    id: "total",
    label: "Total People in Family",
    placeholder: "family members count",
    type: "text",
    required: false,
    value: "1",
    values: [],
    validations: [
      {
        type: "minLength",
        value: "1",
        error_message: "there should be atleast 1 family member"
      },
      {
        type: "maxLength",
        value: "5",
        error_message: "max family members can be 5"
      }
    ]
  }
]

 let validateSchema = yup.object().shape({
     name: yup.string().required("name is required"),
     email: yup.string().email(),
     phoneNumber: yup.number().min(10, "minium 10 numbers"),
     total: yup
       .number()
       .min(1, "minium 1 member")
       .max(5, "max 5 member")
       .required("member is required")    });
  • В данный момент я выполняю итерацию по вышеуказанному массиву и вызываю соответствующие компоненты формы React.
  • Проверка в настоящее время обрабатывается Yup. Мне известно, что вы можете создать статическую схему проверки Yup, как описано выше в переменной 'validateSchema'.
  • Теперь я хочу создать эту схему проверки в зависимости от значений. в массиве formData.validation. Я попробовал некоторые способы в этом codesandbox , но все еще не может понять это. Кроме того, я посмотрел в Yup.lazy, но это кажется мне очень запутанным.

Любая помощь будет оценена :)

Codesandbox

...