我已经使用bootstrap(reactjs中的Form组件)制作了一个表单,但是当我尝试单击Submit按钮时,即使我没有键入任何输入,表单也会被提交。我应该如何验证我的表单,以便在填写所有输入字段时仅提交表单。

表单组件:

class Form extends Component {

render(){
    return(
      <div>
          <div id="center">
              <form>
                    <div className="form-group">
                         <label htmlFor="firstname">First Name:</label>
                         <input type="firstname" className="form-control" id="firstname" onChange={this.setFirstName}/>
                    </div>

                    <div className="form-group">
                         <label htmlFor="lastname">Last Name:</label>
                         <input type="lastname" className="form-control" id="lastname" onChange={this.setLastName}/>
                    </div>

                    <div className="form-group">
                        <label htmlFor="email">Email address:</label>
                        <input type="email" className="form-control" id="email" onChange={this.setEmailId}/>
                    </div>

                    <div className="form-group">
                         <label htmlFor="bankacc">IBAN:</label>
                         <div id="deletebank" className="items">
                         <input type="bankacc" className="form-control" id="bankacc" onChange={this.setIban}/>
                         <button type="button" className="btn btn-default btn-sm">
                            <span className="glyphicon glyphicon-trash"></span>
                         </button>
                         </div>
                    </div>

                    <div className="form-group">
                         <label htmlFor="bankname">Bank Name:</label>
                         <input type="bankname" className="form-control" id="bankname" onChange={this.setBankName}/>
                    </div>

                    <div className="form-group">
                         <button type="button" className="btn btn-success" onClick={this.showUser}>Submit</button>
                    </div>


              </form>
          </div>
      </div>

    )}


}


屏幕截图:

javascript - 如何验证引导表格?-LMLPHP

最佳答案

You can make use of html5's require property for simple form validation

<input type="firstname"
       className="form-control"
       id="firstname"
       required
       onChange={this.setFirstName}/>

Also one suggestion is that, I see you are calling different methods for every
fields. You can simple use

 onChange={this.handleChange}

  handleChange = (e) => {
        const { value, id } = e.target;
        this.setState({ [id]: e.target.value })
    }

  your state can be

  state = {
    lastname: '',
    email: ''
  } etc....

 Your submit button will be

<button type="submit" className="btn btn-success" onSubmit= .
{this.handleSubmit}>Submit</button>

 If you want to customize it, you can follow the link.

 https://stackoverflow.com/questions/41296668/reactjs-form-input-validation

07-28 09:22