Automatically trim white spaces with Yup and Formik

Viewed 29549

I am using a Formik React Form and Yup validation defined on a schema:

export const Contact = yup.object<IContact>().shape({
  contactName: yup
    .string()
    .trim('The contact name cannot include leading and trailing spaces')
    .strict(true)
    .min(1, 'The contact name needs to be at least 1 char')
    .max(512, 'The contact name cannot exceed 512 char')
    .required('The contact Name is required'),
});

Is there a way to have Yup trim white spaces without showing a message? So automatically trimming the spaces when a form is submitted?

3 Answers

Is there a way to have Yup trim white spaces without showing a message

Not in a single transform. The yup transform used by formik is only for validation. You can create a seperate transform to use before passing the data, but its simpler to just valueToUse = userValue.trim() yourself.

You can also trim entered text on the go to completely limit user from using spaces at the end (example uses react native components):

const {handleSubmit, values, errors} =
    useFormik({
        validationSchema: EmailSchema(),
        initialValues: {email: ''},
        onSubmit: values => tryLogin(values.email)
    })

...

<TextInput
    value={values.email}
    onChangeText={text => handleChange('email')(text.trim())}
    error={errors.email}
/>

<Button title='SUBMIT' onPress={handleSubmit} />
Related