Search code examples
reactjsformsemail-validation

React - adding email validation to empty input validation


In React, I'm looking to add email validation (checks for @ and .com) to a form that currently checks for empty input fields.

I found this that does the job but can't figure out how to connect it to onSubmit along w/ my other validation.

Here's the link to this project's codepen for complete code.

Setting initial State for inputs and errors:

constructor() {
super();
this.state = {
  inputs: {
    name: '',
    email: '',
    message: '',
  },
  errors: {
    name: false,
    email: false,
    message: false,
  },
};

}

JS Handling Input, onBlur

updateInput = e => {
this.setState({
  inputs: {
    ...this.state.inputs,
    [e.target.name]: e.target.value,
  },

  errors: {
    ...this.state.errors,
    [e.target.name]: false,
  },
});
};

handleOnBlur = e => {
const { inputs } = this.state;
if (inputs[e.target.name].length === 0) {
  this.setState({
    errors: {
      ...this.state.errors,
      [e.target.name]: true,
    },
  });
}
};

Solution

  • Without refactoring too much of your code, we can just update the updateInput() function to this:

      updateInput = event => {
        const { name, value } = event.target;
    
        if (name === "email") {
          this.setState({
            inputs: {
              ...this.state.inputs,
              [name]: value
            },
            errors: {
              ...this.state.errors,
              email:
                value.includes("@") &&
                value.slice(-4).includes(".com")
                  ? false
                  : true
            }
          });
        } else {
          this.setState({
            inputs: {
              ...this.state.inputs,
              [name]: value
            },
            errors: {
              ...this.state.errors,
              [name]: false
            }
          });
        }
      };
    

    Also see sandbox: https://codesandbox.io/s/conditional-display-input-errors-vfmh5