簡體   English   中英

如何在反應中驗證來自 material-ui 的控制?

[英]How to validate control from material-ui in react?

我使用material-ui和 react。

我想做諸如requiremaxlengthminlength驗證。 根據 material-ui 文檔,我必須使用error道具和helperText來顯示錯誤。 這意味着我必須自己觸發一個函數來檢查控件並顯示錯誤。 :(

如果這是使用反應處理驗證的正確方法,那么文本字段本身無法顯示需要消息(例如)? 我必須自己指定每個錯誤? 例如,在 angular 中,我只需添加requireminlength ,控件就會顯示正確的錯誤。

或者也許有一種簡單的方法來做到這一點?

明白了:) 這里是我的前任:

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>

你需要安裝 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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM