简体   繁体   English

ReactJS 如何验证所有输入然后提交

[英]ReactJS how to validate all inputs then submit

I'm working on a form in ReactJS , I have multiple input (in fiddle it's just a demo, it's about 10-15 inputs in real code) I want to validate all inputs and if all are valid then submit/POST to api, what I tried so far is this JSFiddle我正在处理ReactJS中的form ,我有多个input (在小提琴中,这只是一个演示,实际代码中大约有 10-15 个输入)我想验证所有输入,如果所有输入都有效,然后提交/发布到 api,到目前为止我尝试的是这个JSFiddle

handleChange = (e) => {
  if (e.target.value.length >= 5) {
    this.setState({
      submit: true
    })
  } else {
    this.setState({
      submit: false
    })
  }
}

So, for do this, I define a state called submit , if submit is true , form going to submit and call api .因此,为此,我定义了一个名为submit的 state ,如果submittrue ,则表单将提交并调用api the problem is if user fill and valid one of the inputs, submit set to true , but I want when user valid all inputs then submit should set to true .问题是,如果用户填写并验证其中一个输入,则将submit设置为true ,但我希望当用户验证所有输入时, submit应设置为true

You should have component state to manage the validation of input.您应该有组件 state 来管理输入验证。 Below is my code that I used yours and have my edit:以下是我使用您的代码并进行了编辑:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      submit: false,
      isValid: {
        "1": false,
        "2": false,
        "3": false,
        "4": false,
        "5": false
      }
    };
  }

  handleSubmit = e => {
    e.preventDefault();
    if (this.state.submit) {
      alert("POSTED TO API");
    } else {
      alert("fill the form!");
    }
  };

  checkValid = () => {
    if (
      Object.values(this.state.isValid).filter(value => !value).length === 0
    ) {
      this.setState({ ...this.state, submit: true });
    }
  };

  handleChange = (e, item) => {
    if (e.target.value.length >= 5) {
      this.setState(
        {
          ...this.state,
          isValid: { ...this.state.isValid, [`${item}`]: true }
        },
        this.checkValid
      );
    }
  };

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        submit is: {this.state.submit ? "true" : "false"}
        <br />
        {[1, 2, 3, 4, 5].map(item => {
          return (
            <input
              name={"field" + item}
              type="text"
              onChange={e => {
                this.handleChange(e, item);
              }}
            />
          );
        })}
        <input type="submit" value="ok" />
      </form>
    );
  }
}

export default App;

You can move validation from the handleChange function.您可以从 handleChange function 移动验证。 Change your function like this (you need to set name prop for your inputs):像这样更改您的 function (您需要为您的输入设置名称道具):

handleChange = (e) => {
  const filed = e.target.name;
  let newState = this.state;
  newState[field] = e.target.value;
  this.setState(newState);
}

and in the onSubmit function check if all values are valid and only then call your API.并在 onSubmit function 检查所有值是否有效,然后才调用您的 API。

  submit = (e) => {
    e.preventDefault();
    if(this.validate()){ . //validate function should be defined in your component - there you will have access to the component's state
      //call api
    } else {
     //show errors
    }
  }

Maybe you can try to validate like this you can create validate function then you can implement validate function in your submit function.也许您可以尝试像这样进行验证,您可以创建验证 function 然后您可以在提交 function 中实现验证 function。

 constructor(props, context) {
    super(props, context);

    this.state = {
      email: "",
      user: "",
      submitted: false,
      errors: [],
      errorEmail: false,
      errorUserLenght: false,
    };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.validate = this.validate.bind(this);
  }

 validate(email, user) {
    const errors = [];

    if (email.length < 5) {
      this.setState({ errorEmail: true });
    } else {
      this.setState({ errorEmail: false });
    }
    if (email.split("").filter(x => x === "@").length !== 1) {
      this.setState({ errorEmail: true });
    } else {
      this.setState({ errorEmail: false });
    }

    if (email.indexOf(".") === -1) {
      this.setState({ errorEmail: true });
    } else {
      this.setState({ errorEmail: false });
    }

    if (user.length < 6) {
      this.setState({ errorUserLenght: true });
    } else {
      this.setState({ errorUserLenght: false });
    }


    return errors;
  }

  handleChange(event) {
    const target = event.target;
    const value = target.value;
    const name = target.name;
    this.setState({ [name]: value });
  }

  async handleSubmit(event) {
    event.preventDefault();

   await this.validate(email, password);

  // Here will be your code for POST
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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