How to Change Default Error Text in Yup/Formik?
Asked Answered
K

5

36

If I click on the email input field, the field says "Enter Your Email". This was set by me. However, during I'm typing,when the validation check isn't fulfilled, it says 'enter a valid email' something, which is a default, not written by me.

In case of wrong password, since I am using .matches(), I get my desired text printed on the screen. How can I do so for email as well?

Here's my Yup object:

const schema = Yup.object({
  email: Yup
    .string()
    .email()
    .required('Please Enter your Email'),
  password: Yup
    .string()
    .required('Please Enter your password')
    .matches(
      /^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{8,}$/,
      "Must Contain 8 Characters, One Uppercase, One Lowercase, One Number and one special case Character"
    )
});

This is how my Formik component looks like:

 <Formik
            initialValues={{ email: '', password: '' }}
            onSubmit={(values, actions) => {
              setTimeout(() => {
                alert(JSON.stringify(values, null, 2));
                actions.setSubmitting(false);
              }, 1000);
            }}
            validationSchema={schema}
          >
            {props => {
              const {
                values: { email, password },
                errors,
                touched,
                handleChange,
                isValid,
                setFieldTouched
              } = props;
              const change = (name: string, e: { persist: () => void; }) => {
                e.persist();
                handleChange(e);
                setFieldTouched(name, true, false);
              };
              return (
                <form style={{ width: '100%' }} onSubmit={_ => alert('Submitted!')}>
                  <TextField
                    variant="outlined"
                    margin="normal"
                    id="email"
                    fullWidth
                    name="email"
                    helperText={touched.email ? errors.email : ""}
                    error={touched.email && Boolean(errors.email)}
                    label="Email"      
                    value={email}
                    onChange={change.bind(null, "email")}
                  />
                  <TextField
                    variant="outlined"
                    margin="normal"
                    fullWidth
                    id="password"
                    name="password"
                    helperText={touched.password ? errors.password : ""}
                    error={touched.password && Boolean(errors.password)}
                    label="Password"
                    type="password"
                    value={password}
                    onChange={change.bind(null, "password")}
                  />
</Formik>

In Formik props, errors : An object containing error messages of the field.

enter image description here enter image description here

Kilocycle answered 22/2, 2020 at 21:21 Comment(0)
E
39

I found that the accepted answer is correct but can be incomplete in some cases. Placing the cursor into a field and tabbing out of it can trigger a Yup "type error".

A default Yup type error is a verbose and non-user-friendly thing ;)

I would extend the answer from AndreasT to read:

email:  Yup
.string()
.email('this will be displayed when email is wrong')
.required('this will be displayed when empty')
.typeError('A number is required')

Here is the article that turned me on to this answer.

Enounce answered 21/3, 2020 at 0:29 Comment(0)
P
22

add your preferred error string to your email schema:

email:  Yup
.string()
.email('this will be displayed when email is wrong')
.required('this will be displayed when empty')

codesandbox example: https://codesandbox.io/s/blissful-shape-lijo2

Predation answered 22/2, 2020 at 22:38 Comment(0)
N
5

for custom validations using test method:

serialNumber: Yup.string()
  .max(19, 'invalid')
  .required('required')
  .test({
    name: 'serialNumberErr',
    message: i18next.t('serialNumberErr'),
    test: (value) => customValidator(value),
  }),

Nessi answered 6/5, 2021 at 13:18 Comment(1)
This works for me because I found an option to customize the error message on a min method, thanks!Dibucaine
G
4
  fullname: yup.string()
           .min(3)
           .required('This is rendered if you try to submit an empty email field'),
  email: yup.string()
        .email('This shows when you input an invalid email addres')
        .required('This is rendered if you try to submit an empty email field'),
  password: yup.string()
        .required('This is rendered if you try to submit an empty email field')
        .matches(
           /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]).{8,}$/,
           "This is rendered if the password does not meet requirement"),
  confirmPassword: yup.string()
        .oneOf([yup.ref('password'), null], "Password mismatch")
        .required('This is rendered if you try to submit an empty email field')
Gemmell answered 10/9, 2022 at 9:54 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Beefwood
C
3

In case of handling only string type errors which does not accept message params following syntax works.

signatureImage: Yup.string().required( 'Live Signature is required' ).typeError( 'Live Signature is required' ),
Cameliacamella answered 29/4, 2020 at 10:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.