简体   繁体   中英

How to Change Default Error Text in Yup/Formik?

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.

在此处输入图像描述 在此处输入图像描述

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

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.

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

  fullname: yup.string()
           .min(4)
           .required('This is a required field'),
  email: yup.string()
        .email('Please input a valid email address')
        .required('Email is required'),
  password: yup.string()
        .required('Enter a valid password')
        .matches(
           /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]).{8,}$/,
           "Must Contain 8 Characters, One Uppercase, One Lowercase, One Number and One Special Case Character"),
  confirmPassword: yup.string()
        .oneOf([yup.ref('password'), null], "Password mismatch")
        .required('This field is required')

在仅处理不接受消息参数的字符串类型错误的情况下,以下语法有效。

signatureImage: Yup.string().required( 'Live Signature is required' ).typeError( 'Live Signature is required' ),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM