Home > Back-end >  Form required section in react
Form required section in react

Time:05-04

there is required section in my form also I want to send successfully text after click of submit button. But problem is here when I click submit button, it shows successfully text no matter form is correct or not. Can you help me about that ? I am beginner :)

My react code here

import React, { Component } from "react";

export default class Form extends Component {
  state = {
    name: "",
    surname: "",
    phone: "",
    email: "",
    comments: "",
    // isValid: true,
    succesfully: ""
  };

  /* preventSending = async (e) => {
    await this.setState({ [e.target.name]: e.target.value });
    if (
      this.state.name === "" ||
      this.state.surname === "" ||
      this.state.phone === "" ||
      this.state.email === "" ||
      this.state.comments === ""
    ) {
      this.setState({ isValid: true });
    } else {
      this.setState({ isValid: false });
    }
  };*/

  handleSubmit = (e) => {
    this.setState({
      succesfully: `${this.state.name} you have sent successfully `
    });
  };

  render() {
    return (
      <div className="">
        <form>
          <label htmlFor="name">
            Name :
            <input
              onChange={this.preventSending}
              id="name"
              name="name"
              type="text"
              required
            />
          </label>
          <br />
          <label htmlFor="surname">
            Surname :
            <input
              onChange={this.preventSending}
              id="surname"
              name="surname"
              type="text"
              required
            />
          </label>
          <br />
          <label htmlFor="phone">
            Phone :
            <input
              onChange={this.preventSending}
              id="phone"
              name="phone"
              type="tel"
              required
            />
          </label>
          <br />
          <label htmlFor="email">
            Email :
            <input
              onChange={this.preventSending}
              id="email"
              name="email"
              type="email"
              required
            />
          </label>
          <br />
          <label htmlFor="textArea">
            Comments :
            <textarea
              onChange={this.preventSending}
              id="textarea"
              name="comments"
              required
            />
          </label>
          <br />
          <button
            type="submit"
            // disabled={this.state.isValid}
            onClick={this.handleSubmit}
          >
            Send details{" "}
          </button>
        </form>

        <p>{this.state.succesfully}</p>
      </div>
    );
  }
}

It says I have to add more details but I explained everything clear.

CodePudding user response:

I have to go through your code and try to resolve the errors and get the proper output.

I see that you take the direct state object and update its value, I just corrected that part and also add one error flag in it, so that you can display one informational error message while you click the button without adding the data.

Apart from that, in your form, you take one button which has submit type. As of now I simply update it with type=button, as type=submit will submit the form and redirect us to new URL.

Please let me know if it is useful to you or not.

here is my code

import React, { Component } from "react";

export default class Form extends Component {
    constructor(props) {
        super(props);
        this.state = {
            name: "",
            surname: "",
            phone: "",
            email: "",
            comments: "",
            // isValid: true,
            succesfully: "",
            error: "",
        };
    }

    /* preventSending = async (e) => {
        await this.setState({ [e.target.name]: e.target.value });
        if (
        this.state.name === "" ||
        this.state.surname === "" ||
        this.state.phone === "" ||
        this.state.email === "" ||
        this.state.comments === ""
        ) {
        this.setState({ isValid: true });
        } else {
        this.setState({ isValid: false });
        }
    };*/

    handleChange(event) {
        const target = event.target;
        const value = target.value;
        const name = target.name;

        this.setState({
            [name]: value,
        });
    }

    handleSubmit = (e) => {
        if (
            this.state.name !== "" &&
            this.state.surname !== "" &&
            this.state.phone !== "" &&
            this.state.email !== "" &&
            this.state.comments !== ""
        ) {
            // check valid email or not with regex
            const regexp = /^([\w\.\ ]{1,})([^\W])(@)([\w]{1,})(\.[\w]{1,}) $/;
            let isValidEmail = regexp.test(this.state.email) ? true : false;

            if (isValidEmail) {
                this.setState({
                    succesfully: `${this.state.name} you have sent successfully `,
                    error: "",
                });
            } else {
                this.setState({
                    succesfully: "",
                    error: "Please add proper email",
                });
            }
            } else {
                this.setState({
                    succesfully: "",
                    error: "Please add proper data",
                });
        }
    };

    render() {
        return (
            <div className="">
                <form>
                    <label htmlFor="name">
                        Name :
                        <input
                        onChange={(e) => this.handleChange(e)}
                        id="name"
                        name="name"
                        type="text"
                        value={this.state.name}
                        required
                        />
                    </label>
                    <br />
                    <label htmlFor="surname">
                        Surname :
                        <input
                        onChange={(e) => this.handleChange(e)}
                        id="surname"
                        name="surname"
                        type="text"
                        value={this.state.surname}
                        required
                        />
                    </label>
                    <br />
                    <label htmlFor="phone">
                        Phone :
                        <input
                        onChange={(e) => this.handleChange(e)}
                        id="phone"
                        name="phone"
                        type="tel"
                        value={this.state.phone}
                        required
                        />
                    </label>
                    <br />
                    <label htmlFor="email">
                        Email :
                        <input
                        onChange={(e) => this.handleChange(e)}
                        id="email"
                        name="email"
                        type="email"
                        value={this.state.email}
                        required
                        />
                    </label>
                    <br />
                    <label htmlFor="textArea">
                        Comments :
                        <textarea
                        onChange={(e) => this.handleChange(e)}
                        id="textarea"
                        name="comments"
                        value={this.state.comments}
                        required
                        />
                    </label>
                    <br />
                    <button
                        // type="submit" // use this while you want to submit your form
                        type="button" // I use button to call handleSubmit method and display message
                        // disabled={this.state.isValid}
                        onClick={this.handleSubmit}
                    >
                        Send details
                    </button>
                </form>

                <p>{this.state.succesfully}</p>
                <p>{this.state.error}</p>
            </div>
        );
    }
}

CodePudding user response:

I see that the function prevent sending that you created should work except you misplaced the isValid argument:

if (
      this.state.name === "" ||
      this.state.surname === "" ||
      this.state.phone === "" ||
      this.state.email === "" ||
      this.state.comments === ""
    ) {
      this.setState({ isValid: true }); // should be false
    } else {
      this.setState({ isValid: false }); // should be true
    }

also uncomment disabled and isValid which should be false at the begginning:

// disabled={this.state.isValid}
// isValid = true // should be false
  • Related