28

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

x89
  • 2,798
  • 5
  • 46
  • 110

5 Answers5

32

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.

Michael W.
  • 536
  • 4
  • 5
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

AndreasT
  • 921
  • 6
  • 12
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' ),
Syed Danial
  • 635
  • 1
  • 6
  • 16
3

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),
  }),

Muhammed Moussa
  • 4,589
  • 33
  • 27
1
  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')
TonniPaul
  • 11
  • 3
  • 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](/help/how-to-answer). – Community Sep 14 '22 at 15:30