我想通过表单外部的按钮提交表单并对该表单进行验证。我正在使用react-bootstrap 中的Form 标签。
我的代码未验证表单
<Form
noValidate
validated={validated}
onSubmit={e=> this.handleSubmit(e)}>
<Form.Control
required
placeholder="Product Name"
onChange={e => this.setState({name: e.target.value })}
pattern={"[A-Z a-z]{3,30}"}
/>
</Form>
<button type="button" value="send" onClick={(e) => this.handleSubmit(e)} className={"btn btn-primary"}>Save</button>
handleSubmit(event) {
const form = event.currentTarget;
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
else
this.AddProduct();
this.setState({ validated: true });
}
最佳答案
理想情况下:不要这样做。表单元素是有用的结构元素。
失败了。添加form
属性值等于 id
的按钮表单的属性。
form HTML5
The form element that the button is associated with (its form owner). The value of the attribute must be the id attribute of a
<form>
element in the same document. If this attribute is not specified, the<button>
element will be associated to an ancestor<form>
element, if one exists. This attribute enables you to associate<button>
elements to<form>
elements anywhere within a document, not just as descendants of<form>
elements.
— MDN
关于javascript - 如何通过表单外的按钮提交表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56025301/