Home > Back-end >  Yup errors don't fire before onBlur
Yup errors don't fire before onBlur

Time:03-09

I want this input field's Yup errors to fire as soon as a key is logged for maximum interactivity. However, I'm only getting the errors once I click out of the text field. After the first onBlur event happens and I click back the text field, the next errors are showed in real time.

How can I alter this behavior? I want an error to appear immediately if my first character is not a letter or if my name is not 5-12 characters long.

This is my code:

import ReactDOM from 'react-dom';
import { useFormik } from 'formik'
import * as Yup from 'yup';

function Container(){
  const formik = useFormik({
    initialValues: {
      prodName: ''
    },
    validationSchema: Yup.object(
      {
        prodName : Yup.string().required('This field is required')
        .matches(/^[aA-zZ\s] $/, "Only letters are allowed for this field ")
        .min(5,'Minimum is 5').max(12, 'No more than 12')
        
      }
    )
  })
  
  return(
    <div id='prd-contain'>
      <form onSubmit={formik.handleSubmit}> 
          <label className='prd-labels'>Product name</label>
          <input type="text" id="prodName" name="prodName" value={formik.values.prodName}
                 onChange={formik.handleChange} onBlur={formik.handleBlur}/>
          {formik.touched.prodName && formik.errors.prodName ? (<div>{formik.errors.prodName}</div>) : null}

          <input type="submit" value="Submit"/>
        </form>
    </div>
  )
}

ReactDOM.render(
  <Container />,
  document.getElementById('root')
);

CodePudding user response:

You can simply change

<input type="text" id="prodName" name="prodName" value={formik.values.prodName} onChange={formik.handleChange} onBlur={formik.handleBlur}/>

to

<input type="text" id="prodName" name="prodName" value={formik.values.prodName} onChange={formik.handleChange} onkeyup={formik.handleBlur}/>
  • Related