简体   繁体   中英

How to validate control from material-ui in react?

I using material-ui with react.

I want to do validations such as require and maxlength and minlength . according to material-ui docs I have to use the error prop and helperText to display the error. which mean I have to trigger a function myself that check the control and display the error. :(

I wounder if this is the right way to handle validation with react, the Textfield itself can't display require message (for example)? I have to specify each error myself? for example in angular I just add require or minlength and the control display the correct error.

Or maybe there is an easy way to do it?

got it :) here my ex :

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>

You need to install yup and formik: npm i -s yup formik

Here is a working sample with formik yup and 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM