TypeError:schema [sync吗? 'validateSync':'validate']不是函数

问题描述 投票:0回答:1

我正在尝试使用Formik和Yup验证材料ui表单,但出现错误。

这是我从另一个文件导入的架构。

export const schema = Yup.object({
  email: Yup.string()
    .email('Invalid Email')
    .required('This Field is Required'),
});

这是我使用验证的地方。如果我写validation = schema则没有错误,但是也没有验证。如果我将其更改为{schema},则应用崩溃。

export default function RemoveUserPage() {
  const [isSubmitted, setIsSubmitted] = useState(false);
  const [isRemoved, setIsRemoved] = useState(false);
  const [errorMessage, setErrorMessage] = useState('');

  const [removeUser] = useMutation(REMOVE_USER);

  let submitForm = (email: string) => {
    setIsSubmitted(true);
    removeUser({
      variables: {
        email: email,
      },
    })      
  };

  const formik = useFormik({
    initialValues:{ email: '' },
    onSubmit:(values, actions) => {
       setTimeout(() => {
          alert(JSON.stringify(values, null, 2));
          actions.setSubmitting(false);
          }, 1000);
        },
       validationSchema:{schema}
    })

    const handleChange = (e: ChangeEvent<HTMLInputElement>)=>{
      const {name,value} = e.target;
      formik.setFieldValue(name,value);
     }

  return (
    <div>
              <Form
                onSubmit={e => {
                  e.preventDefault();
                  submitForm(formik.values.email);
                }}>
                <div>
                  <TextField
                    variant="outlined"
                    margin="normal"
                    id="email"
                    name="email"
                    helperText={formik.touched.email ? formik.errors.email : ''}
                    error={formik.touched.email && Boolean(formik.errors.email)}
                    label="Email"
                    value={formik.values.email}
                    //onChange={change.bind(null, 'email')}
                    onChange={formik.handleChange}
                  />
                  <br></br>
                  <CustomButton
                    disabled={!formik.values.email}
                    text={'Remove User'}
                  />
                </div>
              </Form>
    </div>
  );
}

此外,我还想在按钮的isValid!中传递disabled条件,但我不知道该怎么做。我收到了它,因为我可以在道具中编写它,但不确定如何在useFormik()中使用它。

而且,当我提交表单时,文本字段不会自动重置。我该如何解决?

错误:

TypeError: schema[sync ? 'validateSync' : 'validate'] is not a function. (In 'schema[sync ? 'validateSync' : 'validate'](validateData, {
    abortEarly: false,
    context: context
  })', 'schema[sync ? 'validateSync' : 'validate']' is undefined)

[以前,我使用的是<Formik>。在这种情况下,验证是在输入时完成的,例如,如果我输入“ hfs”,它将在输入时立即告诉我无效的电子邮件。但是,对于useFormik(根据下面的答案),它仅在我提交表单后才说无效的电子邮件。我不想发生这种情况,因为一旦提交表单,就会调用该突变。我想分开进行验证。这是我之前使用的]

export default function RemoveUserPage() {
  const [isSubmitted, setIsSubmitted] = useState(false);
  const [isRemoved, setIsRemoved] = useState(false);
  const [errorMessage, setErrorMessage] = useState('');

  const [removeUser] = useMutation<DeleteUserResponse>(REMOVE_USER);

  let submitForm = (email: string) => {
    setIsSubmitted(true);
    removeUser({
      variables: {
        email: email,
      },
    })
      .then(({ data }: ExecutionResult<DeleteUserResponse>) => {
        if (data !== null && data !== undefined) {
          setIsRemoved(true);
        }
      })
  };

  return (
    <div>
      <Formik
        initialValues={{ email: '' }}
        onSubmit={(values, actions) => {
          setTimeout(() => {
            alert(JSON.stringify(values, null, 2));
            actions.setSubmitting(false);
          }, 1000);
        }}
        validationSchema={schema}>
        {props => {
          const {
            values: { email },
            errors,
            touched,
            handleChange,
            isValid,
            setFieldTouched,
          } = props;
          const change = (name: string, e: FormEvent) => {
            e.persist();
            handleChange(e);
            setFieldTouched(name, true, false);
          };
          return (
            <Wrapper>
              <Form
                onSubmit={e => {
                  e.preventDefault();
                  submitForm(email);
                }}>
                <div>
                  <TextField
                    variant="outlined"
                    margin="normal"
                    id="email"
                    name="email"
                    helperText={touched.email ? errors.email : ''}
                    error={touched.email && Boolean(errors.email)}
                    label="Email"
                    value={email}
                    onChange={change.bind(null, 'email')}
                  />
                  <br></br>
                  <CustomButton
                    disabled={!isValid || !email}
                    text={'Remove User'}
                  />
                </div>
              </Form>
          );
        }}
      </Formik>
    </div>
  );
}
javascript reactjs typescript formik yup
1个回答
0
投票

它应该是validationSchema:模式而不是{schema}

之所以无法验证,是因为您没有使用formik的handleSubmit

useFormik({
initialValues:{ email: '' },
onSubmit:(values, actions) => {
   setTimeout(() => {
      alert(JSON.stringify(values, null, 2));
      actions.setSubmitting(false);
      }, 1000);
    },
   validationSchema: schema
})

...

<Form onSubmit={formik.handleSubmit}>
  ...
  <CustomButton
       disabled={formik.touched.email && formik.errors.email ? true : false}
       text={'Remove User'}
  />
  ...
</Form>

它应该使用formik的handleSubmit来获得您在validationSchema上定义的验证

也将formik.touched.email && formik.errors.email传递给禁用的按钮属性。

© www.soinside.com 2019 - 2024. All rights reserved.