Tim von Känel
Tim von Känel

Reputation: 43

Triggering form's submit event manually in React doesn't check required inputs

im trying to find a way to trigger the submit event manually, just like a button with type="submit" would. I found a way to do that, from another post here, but unfortunately it doesn't check if the required inputs contain values and submits the form even when no text was typed into the input:

https://codesandbox.io/s/q92855nz3w

or

import React from "react";
import { render } from "react-dom";

class NameForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = { value: "" };

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    this.setState({ value: event.target.value });
  }

  handleSubmit(event) {
    alert("A name was submitted: " + this.state.value);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <div onClick={this.handleSubmit}>SOME DIV</div>
        <label>
          Name:
          <input
            type="text"
            value={this.state.value}
            onChange={this.handleChange}
            required
          />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

render(<NameForm />, document.getElementById("root"));

Thanks for any help in advance!

Upvotes: 1

Views: 1266

Answers (1)

Tim von K&#228;nel
Tim von K&#228;nel

Reputation: 43

Found a solution to my question:

var form = document.getElementById("form");
form.reportValidity();

Upvotes: 1

Related Questions