1

As seen in the title, I need a form validation in accordance below code. I have tried to validate many times with nodemailer method before and it was working validation. Now I changed my method due to some issues therefore I try another method but I cant not implement that. Can anyone help me, please?

Here is my new contact form and its function.

const Form = () => {
  function sendEmail(e) {
    e.preventDefault();
    emailjs
      .sendForm(
        'servxxxxxxxxxu',
        'tempxxxxxxxxxxxxa',
        e.target,
        'userxxxxxxxxxxxxxxxxxxxx'
      )
      .then((res) => {
        console.log(res);
      })
      .catch((err) => console.log(err));
  }
  return (
    <div className="Contact">
      <div className="wrapper">
        <h1>Contact Form</h1>
        <form onSubmit={sendEmail}>
          <input
            className="input-field"
            type="text"
            name="name"
            placeholder="Name"
          />

          <input
            className="input-field"
            type="text"
            name="user_email"
            placeholder="E-Mail"
          />

          <textarea name="message" rows="4" placeholder="Message" />
          <input type="submit" value="Send" />
        </form>
      </div>
    </div>
  );
};
export default Form;

This is my old validation, may be helpful to you.

const initialState = {
  name: '',
  subject: '',
  email: '',
  message: '',
  sent: false,
  nameError: '',
  subjectError: '',
  emailError: '',
  messageError: '',
};

export default class Validation extends React.Component {
  state = initialState;

  handleName = (e) => {
    this.setState({
      name: e.target.value,
    });
  };
  handleSubject = (e) => {
    this.setState({
      subject: e.target.value,
    });
  };
  handleEmail = (e) => {
    this.setState({
      email: e.target.value,
    });
  };
  handleMessage = (e) => {
    this.setState({
      message: e.target.value,
    });
  };
  validate = () => {
    let nameError = '';
    let subjectError = '';
    let emailError = '';
    let messageError = '';

    if (!this.state.name) {
      nameError = 'Name cannot be blank!';
    }
    if (!this.state.subject) {
      subjectError = 'Subject cannot be blank!';
    }
    if (this.state.message.length < 5) {
      messageError = 'Message cannot be less 5 character!';
    }

    if (!this.state.email) {
      emailError = 'E-mail cannot be blank!';
    } else if (typeof this.state.email !== 'undefined') {
      var mailformat = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
      if (!mailformat.test(this.state.email)) {
        emailError = 'Incorrect e-Mail!';
      }
    }
    if (emailError || nameError || subjectError || messageError) {
      this.setState({ emailError, nameError, subjectError, messageError });
      return false;
    }

    return true;
  };

  handleSubmit = (e) => {
    e.preventDefault();

    const isValid = this.validate();
    if (isValid) {
      console.log(this.state);
      this.sendingMail();
      this.setState(initialState);
    }
  };

  sendingMail = () => {
    let data = {
      name: this.state.name,
      subject: this.state.subject,
      email: this.state.email,
      message: this.state.message,
    };

    axios
      .post('http://127.0.0.1:3001/api/form', data)
      .then((res) => {
        this.setState(
          {
            sent: true,
          },
          this.resetForm()
        );
      })
      .catch(() => {
        console.log('message not sent');
      });
  };

  resetForm = () => {
    this.setState({
      name: '',
      subject: '',
      email: '',
      message: '',
    });

    setTimeout(() => {
      this.setState({
        sent: false,
      });
    }, 3000);
  };
}
2
  • 1
    There's a number of off the shelf solutions for this. I've used React Hook Form before to great effect. Commented Sep 22, 2021 at 13:22
  • Thanks! I fixed it with this way. Commented Sep 23, 2021 at 21:17

1 Answer 1

2

you can merge all handle methods into 1

 state = initialState;

  handleInput = (e , stateName) => {
    this.setState({ [`${stateName}`]: e.target.value})
  };
 

with this jsx

<input type="text" placeholder="name" onChange={(e)=>{this.handleInput('name' ,e)}}

validation

    var States = [ this.state.name, this.state.subject , this.state.email , this.state.message]
        States.forEach((stateKey)=>{
          if (!stateKey) this.setState({Error: `${stateKey} could not be blank`})
        })
    if (this.state.message.length < 5)this.setState({Error:'Message cannot be less 5 character!})
        
    if (this.state.Error) return false;
    return true
Sign up to request clarification or add additional context in comments.

2 Comments

Thankful for your suggestion.
Welcome brother

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.