将YUP与Material-UI TextField一起使用

时间:2019-07-12 13:31:25

标签: material-ui rect formik yup

我正在尝试将表单转换为使用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 个答案:

答案 0 :(得分:0)

我首先看到的是您已经剥离了标准的<Field />组件,并直接更改为<TextField /><Field />组件实际上是一个特殊的组件,根据fomik文档,该组件“将自动将输入连接到Formik。它使用name属性与Formik状态进行匹配”。结果,我相信formik不再实际处理输入,而是这些是不受控制的组件(没有通过react状态设置值的html组件)。使用formik不再处理输入时,Yup验证将内置到formik中,并且无法通过模式属性正确使用。

要解决此问题,您可以使用一个库(实质性用户界面建议该库-https://github.com/stackworx/formik-material-ui),也可以为Formik制作自定义输入组件。这样,您就可以将<Field />的组件属性设置为可以正确地将材料UI与<Field />公开的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"
/>

您可以在https://jaredpalmer.com/formik/docs/api/field字段的Formik文档中找到示例和有关此的更多信息