Home > Software design >  Change css when yup validate input
Change css when yup validate input

Time:07-20

I have this Formik Form with Yup validation :

<Form>

   <div className="mt-3">
      <label className="font-semibold">Nom</label>
      <Field className={`mt-2 rounded-md w-full py-2 px-3 ${errors.lastname ? 'border-2 border-red-500 error-form error-form' : 'border'}`}
             name="lastname"
             type="text"
             placeholder="Votre nom"
             />
       {errors.lastname &&
           <div className="text-red-500 text-sm">{errors.lastname}</div>}

       [...]
    </div>

I disable the verification before submit (because I didn't want the visitor to be alarmed on every input even before he filled it :

validateOnChange={false}
validateOnBlur={false}

Everything works fine. But now I want to set a green border on the input (when I click on Submit button) to the Fields that are OK for Yup.

I already do it with red borders when error.

I tried className={`mt-2 rounded-md w-full py-2 px-3 ${errors.message ? 'border-2 border-red-500 error-form' : 'border'} ${!errors.lastname ? 'border-2 border-green-500' : ''}`} but this set all my fields in green border even before the submit.

Any idea ?

CodePudding user response:

Yes, it will be applied before you even submit the form as you're just checking if it has error or not. Obviously in the beginning, since there are no errors, all borders will be painted green.

Apply the same code conditionally on submit button click and it will work.

Or to make things more clean, you can dynamically add a class like form_submitted on submit click and then use the following CSS

.form_submitted  input {
   border-color: green;
}

.form_submitted  input.error {
   border-color: red;
}
  • Related