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,
},
});
}
};
Without refactoring too much of your code, we can just update the
updateInput()
function to this:Also see sandbox: https://codesandbox.io/s/conditional-display-input-errors-vfmh5
one possible way is to add a conditioning to your code like so