使用YUP和Material-UI的TextField

5

我正在尝试将一个表单转换为使用Material-ui TextField。如何使我的YUP验证与其配合工作?这是我的代码:

import * as React from "react";
import { useState } from 'react';
import { Row, Col } from "react-bootstrap";
import TextField from '@material-ui/core/TextField';
import Button from '@material-ui/core/Button';
import { Formik, Form, Field, ErrorMessage } from "formik";
import * as Yup from "yup";
import axios from "axios";

import Error from "../../Error";

type FormValues = {
  username: string;
  password: string;
  repeatPassword: string;
  fullName: string;
  country: string;
  email: string;
};

export default function CreatePrivateUserForm(props: any) {

  const [errorMessage, setErrorMessage] = useState();

  const createPrivateAccountSchema = Yup.object().shape({
    username: Yup.string()
      .required("Required")
      .min(8, "Too Short!")
      .max(20, "Too Long!")
      .matches(/^[\w-.@ ]+$/, {
        message: "Inccorect carector"
      }),
    password: Yup.string()
      .required("Required")
      .min(10, "Too Short!")
      .max(100, "Too Long!")
      .matches(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^a-zA-Z\d\s:]).*$/, {
        message: "Password need to contain 1 uppercase character (A-Z), 1 lowercase character (a-z), 1 digit (0-9) and 1 special character (punctuation)"
      }),
    repeatPassword: Yup.string()
      .required("Required")
      .oneOf([Yup.ref("password")], "Passwords must match")
  });



  function handleSuccess() {
    alert("User was created");
  }

  async function handleSubmit(values: FormValues) {
    const token = await props.googleReCaptchaProps.executeRecaptcha("CreatePrivateUser");

    const headers = {
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
        recaptcha: token
      }
    };

    const body = { username: values.username, password: values.password, repeatPassword: values.repeatPassword };

    const url = "xxx";

    try {
      const response = await axios.post(url, body, headers);
      if (response.status === 201) {
        handleSuccess();
      }
      if (response.status === 400) {
        console.log("Bad Request ...");
        setErrorMessage('Bad Request');
      } else if (response.status === 409) {
        console.log("Conflict ...");
        setErrorMessage('Conflict');
      } else if (response.status === 422) {
        console.log("Client Error ...");
        setErrorMessage('Client Error');
      } else if (response.status > 422) {
        console.log("Something went wrong ...");
        setErrorMessage('Something went wrong');
      } else {
        console.log("Server Error ...");
        setErrorMessage('Server Error');
      }
    } catch (e) {
      console.log("Fejl");
    }
  }



  return (
    <React.Fragment>
      <Row>
        <Col xs={12}>
          <p>Please register by entering the required information.</p>
        </Col>
      </Row>
      <Row>
        <Col xs={12}>
          <Formik
            initialValues={{ username: "", password: "", repeatPassword: "" }}
            validationSchema={createPrivateAccountSchema}
            onSubmit={async (values, { setErrors, setSubmitting }) => {
              await handleSubmit(values);
              setSubmitting(false);
            }}>
            {({ isSubmitting }) => (
              <Form>
                {errorMessage ? <Error errorMessage={errorMessage} /> : null}
                <Row>
                  <Col xs={6}>
                    <Row>
                      <Col xs={12}>
                        <TextField
                          label="Username"
                          helperText={touched.username ? errors.username : ""}
                          error={touched.username && Boolean(errors.username)}
                          type="text"
                          name="username"
                          margin="normal"
                          variant="filled"
                        />
                        <ErrorMessage name='username'>{msg => <div className='error'>{msg}</div>}</ErrorMessage>
                      </Col>
                    </Row>
                    <Row>
                      <Col xs={12}>
                        <label htmlFor='password'>Password:</label>
                        <Field type='password' name='password' />
                        <ErrorMessage name='password'>{msg => <div className='error'>{msg}</div>}</ErrorMessage>
                      </Col>
                    </Row>
                    <Row>
                      <Col xs={12}>
                        <label htmlFor='repeatPassword'>Repeat password:</label>
                        <Field type='password' name='repeatPassword' />
                        <ErrorMessage name='repeatPassword'>{msg => <div className='error'>{msg}</div>}</ErrorMessage>
                      </Col>
                    </Row>
                  </Col>
                </Row>
                <Row>
                  <Col xs={12}>
                    <button type='submit' disabled={isSubmitting}>
                      Create User
                      </button>
                  </Col>
                </Row>
              </Form>
            )}
          </Formik>
        </Col>
      </Row>
    </React.Fragment>
  );
}
1个回答

4
我能看到的第一件事是你已经取出了标准的formik <Field /> 组件,并直接改为使用<TextField />。根据formik文档,<Field /> 组件实际上是一个特殊组件,能够自动将输入与formik连接起来。它使用名称属性与Formik状态进行匹配。因此,我认为formik不再处理这些输入,而是变成了不受控制的组件(由React状态设置值的HTML组件)。由于formik不再处理输入,所以通过模式prop使用的内置于formik中的Yup验证将无法正确工作。
要解决这个问题,您可以使用库(Material UI建议使用此库-https://github.com/stackworx/formik-material-ui),或为formik创建自定义输入组件。这允许您将<Field /> 的component prop设置为可以正确连接 Material UI 和 formik 数据的组件。
const CustomTextInput = ({
    field, // { name, value, onChange, onBlur }
    form: { touched, errors }, // also values, setXXXX, handleXXXX, dirty, isValid, status, etc.
    ...props
}) => (
    <div>
        <TextField
            error={_.get(touched, field.name) && _.get(errors, field.name) && true}
            helperText={_.get(touched, field.name) && _.get(errors, field.name)}
            {...field}
            {...props}
        />
    </div>
)

然后在你的表单中,你可以这样做:

<Field
    name="fieldName"
    component={CustomTextInput}
    label="You can use the Material UI props here to adjust the input"
/>

您可以在formik文档的field部分找到示例和更多信息 - https://jaredpalmer.com/formik/docs/api/field


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接