在数据传到后端之前在React中进行表单验证

时间:2019-04-18 18:52:41

标签: reactjs

我想在表单输入字段到达后端之前捕获验证错误。我想在返回语句中附加一些JSX代码,详细说明错误消息

我似乎无法想出一个遍历对象状态并在this.state.formErrors中为每个状态提供错误消息的解决方案,我也不确定一旦提交表单后如何追加一些JSX。 / p>

export default class UserSignUp extends Component {

  state = {
    firstName: '',
    lastName: '',
    emailAddress: '',
    password: '',
    confirmPassword: '',
    isSignedIn: false,

    formErrors: {
      firstName: "",
      lastName: "",
      email: "",
      password: ""
    }
  };

  onSubmit = (event) => {
    event.preventDefault();


    // I WOULD LIKE TO CATCH THE ERRORS RIGHT HERE BEFORE THE AXIOS.POST CALL AND INSERT SOME JSX IN THE RETURN STATEMENT


    if (this.state.password === this.state.confirmPassword){
      axios.post(`http://localhost:5000/api/users`, {
        firstName: this.state.firstName,
        lastName: this.state.lastName,
        emailAddress: this.state.emailAddress,
        password:this.state.password,
        isSignedIn: true
      }).then(() => {
        this.props.history.push('/courses');
      }).catch(err => {
        console.log(err)
      });
    };
  };

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

  cancelSignUp = (event) => {
    event.preventDefault();
    this.props.history.push("/");
  };

  render(){
    return (
    <div className="bounds">
      <div className="grid-33 centered signin">
        <h1 className="append">Sign Up</h1>
        <div>

          <form onSubmit = {this.onSubmit}>
            <div>
              <input id="firstName" name="firstName" type="text" placeholder="First Name" onChange={this.handleChange}/>
            </div>


            /* I omitted the rest of this form element for clarity */
//

所以我的计划是遍历状态(名字,姓氏等),然后,如果状态为formErrors对象为空,则我想附加一条消息。最后,如果可能的话,我想在我的表单元素之前附加这样的内容!

<h2 className="validation--errors--label">Validation errors</h2>
 <div className="validation-errors">
  <ul>
   <li>{this.state.formErrors.firstName}</li>
   <li>{this.state.formErrors.lastName}</li>
  </ul>
 </div> 

2 个答案:

答案 0 :(得分:1)

您可以在渲染方法中使用条件渲染。如果触摸了输入并且为空,则将显示错误。您还需要为每个输入定义错误消息。这是一个输入一个示例:

    class App extends Component {
  state = {
    name: "",
    touched: false
  };

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

  handleBlur = event => {
    this.setState({ touched: true });
  };

  render() {
    const { name, touched } = this.state;
    return (
      <div>
        <input
          value={name}
          onChange={this.handleChange}
          name="name"
          onBlur={this.handleBlur}
        />
        {touched && name === "" && "Put your name please"}
      </div>
    );
  }
}

答案 1 :(得分:1)

当然,您可以自己处理表单验证。但是对于更复杂的表单及其验证,通常更容易避免重新发明轮子并使用第三方软件包。

我个人推荐并使用Formik,它轻巧而强大。