Как изменить текст ошибки по умолчанию в Yup / Formik? - PullRequest
0 голосов
/ 23 февраля 2020

Если я нажму на поле ввода адреса электронной почты, в поле появится сообщение «Введите адрес электронной почты». Это было установлено мной. Тем не менее, во время ввода текста, когда проверка проверки не выполняется, он говорит «введите действительный адрес электронной почты» что-то, что по умолчанию, не написано мной.

В случае неправильного пароля, так как Я использую .matches (), я получаю желаемый текст на экране. Как я могу сделать это и для электронной почты?

Вот мой объект Yup:

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"
    )
});

Вот так выглядит мой компонент Formik:

 <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>

В Formik реквизиты, ошибки: объект, содержащий сообщения об ошибках поля.

enter image description here enter image description here

Ответы [ 3 ]

2 голосов
/ 21 марта 2020

Я обнаружил, что принятый ответ правильный, но в некоторых случаях может быть неполным. Помещение курсора в поле и его выделение может вызвать Yup " error type ".

Ошибка типа Yup по умолчанию - многословная и не удобная для пользователя вещь;)

Я бы расширил ответ от AndreasT следующим образом:

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

Вот статья , которая подтолкнула меня к этому ответу.

1 голос
/ 23 февраля 2020

добавьте предпочитаемую строку ошибки в вашу схему электронной почты:

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

пример кода и коробки: https://codesandbox.io/s/blissful-shape-lijo2

0 голосов
/ 29 апреля 2020

В случае обработки только ошибок строкового типа, которые не принимают параметры сообщения, следующие за синтаксисом работают.

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