validation message not hiding automatically when input field fill correctly

Viewed 41

i am new in react, and try to create mutliple step form using reactjs, Material-ui, in this form validation, and submit buttons work perfectly fine. but i have one issue with the code that, filed is empty and i try to go to second step, it troughs error, but when i fill that filed. error still shows. and then finally i click on next after filling it and come back to first step. it will disappear. i want that when i type in active error, error message automatically disappear.

DEMO is HERE

1 Answers

You should create a onChangeField function in MultiStepForm and set it as onChange in all you field. So you can validate if errors includes the field

MultiStepForm.js

const onChangeField = (fieldName, value) => {
    setFormData({ ...formData, [fieldName]: value });
    if (errors.includes(fieldName)) checkValidation(activeStep);
};

StepOne.js

<TextField
    required
    type="text"
    name="firstName"
    style={{ width: "100%", margin: "1rem 0" }}
    label="First Name"
    variant="outlined"
    value={formData.firstName}
    error={errors.includes("firstName")}
    onChange={(event) => onChangeField("firstName", event.target.value)}
/>

<TextField
    style={{ width: "100%", marginBottom: "1rem" }}
    label="Last Name"
    variant="outlined"
    name="lastName"
    required
    error={errors.includes("lastName")}
    type="text"
    value={formData.lastName}
    onChange={(event) => onChangeField("lastName", event.target.value)}
/>
<TextField
    style={{ width: "100%", marginBottom: "1rem" }}
    label="Email"
    variant="outlined"
    name="email"
    required
    error={errors.includes("email")}
    type="email"
    value={formData.email}
    onChange={(event) => onChangeField("email", event.target.value)}
/>

codesandbox hope it help!

Related