Notice: You can model this logic to develop, write better and best practice for all fields email, age, phone, ... in your react project
You can try this and edit your codesandbox:
Add new state : invalidFields for store invalid fields:
state = {
user: {
name: "",
email1: "",
email2: "",
age: "",
city: "",
phone: ""
},
invalidNumber: false,
invalidEmail: false,
invalidFields: [], // Add this line
submitted: false
};
and then edit your conditions in handleChange function :
add name to this.validateEmail(value, name);
if (name === "email1") {
this.validateEmail(value, name); // add name
}
if (name === "email2") {
this.validateEmail(value, name); // add name
}
if(name === "age") {
this.validateNumber(value, name); // add name
}
if(name === "phone") {
this.validateNumber(value, name); // add name
}
and then change your validateEmail function : Edited
validateEmail = (value, name) => {
const regex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (value && !regex.test(value)) {
// add invalidFields to this.setState
this.setState({ invalidEmail: true, invalidFields: [...this.state.invalidFields, name] });
} else {
// add invalidFields to this.setState and then filter
this.setState({ invalidEmail: false, invalidFields: this.state.invalidFields.filter(item => item !== name) });
}
};
and finally change your condition for show error: Edited
// email1
{submitted && this.state.invalidFields.includes('email1') && (
<div style={{ color: "red" }}>Email is invalid</div>
)}
// email2
{submitted && this.state.invalidFields.includes('email2') && (
<div style={{ color: "red" }}>Email is invalid</div>
)}