如何在反应中从Material-UI验证控制?

时间:2019-12-04 10:37:18

标签: reactjs material-ui

我将material-ui与React配合使用。

我想进行诸如requiremaxlengthminlength之类的验证。根据material-ui文档,我必须使用error属性和helperText来显示错误。这意味着我必须自己触发一个函数,以检查控件并显示错误。 :(

如果这是通过react处理验证的正确方法,我会很伤心,Textfield本身无法显示要求消息(例如)?我必须自己指定每个错误?例如在角度中,我只需添加requireminlength,控件就会显示正确的错误。

或者也许有一种简单的方法?

2 个答案:

答案 0 :(得分:0)

得到它:)这是我的前妻:

import { Link } from 'react-router-dom';
import useForm from "react-hook-form";
import * as yup from 'yup';

const LoginFormSchema = yup.object().shape({
    password: yup.string().required().min(4),
    username: yup.string().required().min(4)
});

export function LoginForm(props) {

    const { register, handleSubmit, watch, errors } = useForm({ defaultValues, validationSchema: LoginFormSchema });
    const onSubmit = data => { props.onSubmit(data); }
     <div className="form-container">
            <form className="form" onSubmit={handleSubmit(onSubmit)}>
                <div className="form-header">
                    <i className="material-icons">
                        account_circle
                            </i>
                    <h2>Login Form</h2>
                </div>

                <TextField name="username" label="username" inputRef={register} />
                <span className="error-message">
                    {errors.username && errors.username.type === "required" && "username is required"}
                    {errors.username && errors.username.type === "min" && "username required to be more than 4 characters"}
                </span>

                <TextField type="password" name="password" label="password" inputRef={register} />
                <span className="error-message">
                    {errors.password && errors.password.type === "required" && "password is required"}
                    {errors.password && errors.password.type === "min" && "password required to be more than 4 characters"}
                </span>


            </form>

答案 1 :(得分:0)

您需要安装yup和formik:npm i -s yup formik

这是一个带有formik yup和material-ui的工作示例:

import React from "react";
import { Formik, Form, useField } from "formik";
import { TextField } from "@material-ui/core";
import * as yup from "yup";

//Reusable Textbox
const MyTextField = ({
  placeholder,
  type = "normal",
  ...props
}) => {
  const [field, meta] = useField<{}>(props);
  const errorText = meta.error && meta.touched ? meta.error : "";
  return (
    <TextField
      variant="outlined"
      margin="normal"
      type={type}
      placeholder={placeholder}
      {...field}
      helperText={errorText}
      error={!!errorText}
    />
  );
};

const validationSchema = yup.object({
  username: yup
    .string()
    .required()
    .max(30)
    .min(2)
    .label("Username"),
  password: yup
    .string()
    .required()
    .max(30)
    .min(2)
    .label("Password")
});

const Signin = ({ history }) => {
  return (
    <div className="SignupOuter">
      <Formik
        validateOnChange={true}
        initialValues={{
          username: "",
          password: "",
          loading: false
        }}
        validationSchema={validationSchema}
        onSubmit={async (data1, { setSubmitting }) => {
                       setSubmitting(true);
        //Call API here
        }}
      >
        {({ values, errors, isSubmitting }) => (
          <Form className="Signup">            
            <MyTextField placeholder="Username" name="username" />
            <MyTextField
              placeholder="Password"
              name="password"
              type="password"
            />            
          </Form>
        )}
      </Formik>
    </div>
  );
};

export default Signin;