无法验证材料UI表单中的错误

时间:2020-07-28 05:10:30

标签: javascript reactjs material-ui

我正在尝试使用JOI验证关于react,material ui的表单错误,但是它不起作用。我感到困惑,因为即使在我的validate函数中,也无法看到console.log()结果。显示错误时,我不明白我没有得到什么。 ...

import React from "react";
import "./styles.css";

import Joi from "joi-browser";
import { Button, TextField } from "@material-ui/core";

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: {
        email: "",
        password: ""
      },
      errors: {}
    };
  }

  schema = {
    email: Joi.string()
      .email({ minDomainSegments: 2 })
      .required(),
    password: Joi.string()
      .max(255)
      .required()
  };

  validate = () => {
    const result = Joi.validate(this.state.data, this.schema, {
      abortEarly: false
    });
    //console.log(result);
    if (!result.error) return null;
    const errors = {};
    for (let item of result.error.details) {
      errors[item.path[0]] = item.message;
    }
    return errors;
  };

  handleSubmit = e => {
    e.preventDefault();
    const errors = this.validate();
    //console.log(errors);
    this.setState({ errors: errors || {} });
    if (errors) return;
  };

  handleChange = e => {
    const data = { ...this.state.data };
    data[e.currentTarget.name] = e.currentTarget.value;
    this.setState({ data });
  };

  render() {
    console.log(this.state);
    const emailerror = this.state.errors.hasOwnProperty("email") ? "#f00" : "";
    const passworderror = this.state.errors.hasOwnProperty("password")
      ? "#f00"
      : "";

    console.log(emailerror);

    const data = this.state.data;
    return (
      <div className="App">
        <form noValidate onSubmit={this.handleSubmit}>
          <TextField
            variant="outlined"
            name="email"
            label="Email"
            type="email"
            value={data.email}
            onChange={this.handleChange}
            fullWidth
            error={emailerror}
          />

          <TextField
            variant="outlined"
            name="password"
            label="Password"
            type="password"
            onChange={this.handleChange}
            value={data.password}
            fullWidth
            error={passworderror}
          />
          <Button
            fullWidth
            variant="contained"
            onClick={() => {
              console.log("hello");
            }}
            style={{
              marginTop: 25,
              color: "white",
              backgroundColor: "rgb(0, 64, 128)"
            }}
          >
            submitted
          </Button>
        </form>
      </div>
    );
  }
}

... 我的示例代码是https://codesandbox.io/s/hopeful-sea-4gmty?file=/src/App.js:0-2488

1 个答案:

答案 0 :(得分:0)

validate函数存在问题:

validate = () => {
    const result = Joi.validate(this.state.data, this.schema, {
      abortEarly: false
    });

    if (!result.error) return null;

    const errors = {};

    for (let item of result.error.details) {
      errors[item.path[0]] = item.message;
    }

    return errors;
  };

for循环中,为每个验证错误添加一个新属性。属性名称是错误的item.path首字母

然后在render函数中检查this.state.errors是否具有名称为emailpassword的属性。

render() {
  const emailerror = this.state.errors.hasOwnProperty("email") ? "#f00" : "";
  const passworderror = this.state.errors.hasOwnProperty("password")
    ? "#f00"
    : "";

  // ...
}

它没有,因为在验证错误的情况下,属性的名称为ep

要解决此问题,请更改for函数内的validate循环:

errors[item.path] = item.message;

并在handleSubmit单击上使用<Button />功能(因为现在只需console.log):

<Button onClick={(e) => this.handleSubmit(e)}>