0

I am using Formik and Yup validation for my form which has firstname ,lastname & username. Username should be without spaces so I am using a onChange event and value. Yup validation is working for firstname and Lastname but not for username. When logging my values found out that username is not getting updated. I am a newbie please help me out. Thanks in advance.

const CustomTextInput =({label, ...props}) =>{
  const [field, meta] = useField(props);

  return(
    <>
    <label className="required" htmlFor={props.id || props.name}>{label}</label>
    {meta.touched && meta.error ? (
      <div className="error">{meta.error}</div>
    ):null}
    <input className="text-input" {...field} {...props}/>
    </>
  )
}

function App(){
const [regnum, Setreg]= useState("");

function avoid(e){
  Setreg(e.target.value.replace(/\s+/g,''));
}

return(
    <Styles>
      <Formik
      initialValues={{
        firstname:'',
        lastname: '',
        username:'',
        phone1:'',
        email:''
      }}
      validationSchema={
        Yup.object({
          firstname: Yup.string()
            .required('Required'),
          lastname: Yup.string()
            .required('Required'),
          username: Yup.string()
            .min(4,"Username should be greater than 4 characters")
            .max(15,"Wooah! Username cannot be that big")
            .required('Required'),
         })
      }
 onSubmit= {(values, { setSubmitting , resetForm }) => {
        
            setTimeout(()=>  {
                //My api call here
             resetForm()
             setSubmitting(false);
            },2000)
            }
            }>

{props => (
          <Form>
           <CustomTextInput label="First Name" name="firstname" type="text" placeholder="first Name"/>
           <CustomTextInput label="Last Name" name="lastname" type="text" placeholder="Last Name"/>
           <CustomTextInput label="UserName" name="username" type="text" value={regnum} onChange={(event)=>avoid(event)} placeholder="Spaces will be removed"/> 
<div>
            <button type="submit" >{props.isSubmitting ? "Loading..." : "Submit"}</button>
            </div> 

</Form>
</Formik>
    </Styles>
    );
}

export default App; 

M. Saran
  • 13
  • 1
  • 6

1 Answers1

0

The question is, do you want to prevent the user from using a username with spaces? If so, the easiest way is to do it through yup.

  validationSchema={
    Yup.object({
      firstname: Yup.string()
        .required('Required'),
      lastname: Yup.string()
        .required('Required'),
      username: Yup.string()
        .required('Required').matches("/\s/", "Cannot contain spaces"),
     })
  }

Otherwise, if you allow the user to write the username with spaces, but you want it for whichever reasons without spaces, you have to manipulate the data in the submitHandler.

By giving it a custom onChange handler to username, you overrode formik since formik uses it's onChange under the hood. Manipulate the data in the submitHandler, prior to submitting, let formik do it's thing.

tachko
  • 161
  • 1
  • 8
  • I am a newbie to react can you tell me how to do it please?? – M. Saran Sep 01 '20 at 23:06
  • Sure, I want the event to be done from the function only. Is there any way to Manipulate the data in the submit handler – M. Saran Sep 02 '20 at 07:30
  • I have updated the code and can you tell me is there any way to add this field to submit handler so that it shows error prior to submitting – M. Saran Sep 02 '20 at 10:36