简体   繁体   中英

How to submit a form through a button outside the form?

I want to submit a form through a button which is outside the form and do the validation to that form. I'm using the Form tag from react-bootstrap.

My code doesn't validate the 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 });
}

Ideally: Don't do that. Form elements are a useful structural element.

Failing that. Add a form attribute to the button with the value equal to the id attribute of the form.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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