0
votes

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; 

1
Where does Setreg comes from? Please show the code for thatVencovsky
Setreg is the state I am using, const [regnum, Setreg]= useState("");M. Saran
@Vencovsky I have the code, Can you help me with a solution?M. Saran

1 Answers

0
votes

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.