Automatically trim white spaces with Yup and Formik
Asked Answered
P

5

25

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?

Pak answered 26/2, 2020 at 22:13 Comment(1)
can you show your complete code?Maynord
D
25

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.

Deity answered 26/2, 2020 at 22:21 Comment(1)
Thanks. Ill probably end up just showing the message for now on submit.Pak
S
2

You can do:

onSubmit={(values) => {
  const castValues = Contact.cast(values)
})

reference: https://github.com/jaredpalmer/formik/issues/473#issuecomment-499476056

Sedgemoor answered 23/12, 2021 at 5:20 Comment(3)
Thanks but that's not what I'm after. I know it can be done this way but the question was around doing it automatically. So the idea was to do it without manual code manipulation. I created a my own separate transform to do this.Pak
what is the Contact?Mesic
Schema ValidationHereof
E
2

You can listen to the onBlur() event. Then trim the string to actually fix any trailing or leading spaces:

onBlur={() => setFieldValue('email', values.)}

Additionally, to trimming for Yup for validation:

export const Contact = yup.object<IContact>().shape({
  contactName: yup
    .string()
    .trim()
    .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'),
});
Earplug answered 30/3, 2023 at 3:53 Comment(0)
L
1

I was able to achieve automatic removal of white spaces in an email field by overriding the onChange method from formik object. This is not the best solution to this but it works fine, especially where spaces are not allowed anywhere in the input field.

const { errors, touched, getFieldProps } = formik;

const { onChange } = getFieldProps('email');

const emailFieldProps = {
  ...getFieldProps('email'),
  onChange: (e) => {
    e.target.value = e.target.value.trim();
    onChange(e);
  },
};
  
return (
  ...
    <TextField
      {...emailFieldProps}
      error={Boolean(touched.email && errors.email)}
      helperText={touched.email && errors.email}
    />
  ...
)
Lifework answered 5/12, 2022 at 18:36 Comment(0)
F
0

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} />
Falconet answered 17/6, 2022 at 14:11 Comment(1)
This does not answer the question as the question is how to Automatically trim white spaces with Yup and Formik.Pak

© 2022 - 2024 — McMap. All rights reserved.