isso kd
isso kd

Reputation: 389

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 });
}

Upvotes: 2

Views: 6539

Answers (1)

Quentin
Quentin

Reputation: 943142

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

Upvotes: 4

Related Questions