React Forms - 使用OnClick()单击“提交”按钮时,输入模式验证将丢失

时间:2017-11-24 20:02:08

标签: forms reactjs

我的表单验证在我的输入字段中定义。它们是“必需的”并且具有“模式”。当我单击我的提交按钮时,它会正确地告诉我是否有任何字段无效。但是,我需要我的按钮来实际做某事。因此,当我添加onClick = {this.someFunction}时,我的表单验证突然完全丢失,无论如何都会提交我的请求。我该如何解决这个问题?

  saveTicket=(event)=>{
event.preventDefault();
this.setState({submit:1})

}

          <form>
        <input required className="form-control" id="name" placeholder="Event Name" defaultValue={this.state.name} onChange={this.updateName}/>
        <input required className="form-control" id="date" pattern="\d{4}-\d{2}-\d{2}" defaultValue={this.state.date} onChange={this.updateDate} placeholder="Date (YYYY-MM-DD)"/>
        <input required className="form-control" id="seat" defaultValue={this.state.seat} onChange={this.updateSeat} placeholder="Seat"/>
        <br/><label>Price in TikTik Coins</label><input type="number" min="1" pattern="\d+" defaultValue={this.state.pprice} className="form-control" id="seat" onChange={this.updatePPrice} placeholder="Sale Price"/>
        <label>Max Resale Price in TikTik Coins</label>
        <input required className="form-control" id="pprice" type="number" min="1" pattern="\d+" defaultValue={this.state.sprice} onChange={this.updateSprice} placeholder="Max Resale Price"/>
        <i>This ticket can never be sold above the Max Resale Price.</i>
        <button className="btn btn-lg btn-primary btn-block" onClick={this.saveTicket}>Create Ticket</button>
      </form>

1 个答案:

答案 0 :(得分:0)

尝试将onSubmit函数分配给表单上的pattern事件,而不是直接将其分配给按钮,因此它不会覆盖验证HTML5属性所需的提交事件正在使用(required<form onSubmit={this.saveTicket}> <input required ... etc /> <input required ... etc /> <button className="btn btn-lg btn-primary btn-block">Create Ticket</button> <form> ):

PackageManager manager = reactContext.getPackageManager();