0

我在表单中使用了甲酸,所以这是我的 HTML

<form onSubmit={handleSubmit} className={css.loginForm}>
            <Input
              variant='standard'
              textAlign='center'
              placeholder='Password'
              id='password'
              name='password'
              type='password'
              value={values.password}
              onChange={handleChange}
              onBlur={handleBlur}
              autoFocus
              error={errors.password && touched.password}
            />
            <Input
              variant='standard'
              textAlign='center'
              placeholder='Repeat Password'
              id='repeatPassword'
              name='repeatPassword'
              type='password'
              value={values.repeatPassword}
              onChange={handleChange}
              onBlur={handleBlur}
              autoFocus
              error={errors.repeatPassword && touched.repeatPassword}
            />
  {errors.repeatPassword ? (
         <div>{errors.repeatPassword}</div>
       ) : null}
         <Button
          variant='primary'
          theme='light'
          type='submit'
          disabled={!!errors.password || !!errors.repeatPassword}>
          <Typography variant='h1'>Reset Password</Typography>
        </Button>
    </form>

所以现在,我正在使用如下验证:

 validationSchema: Yup.object().shape({
    password: Yup.string().required('Password is required'),
    repeatPassword: Yup.string()
    .required('')
    .oneOf([Yup.ref('password'), null], 'Passwords must match')
  }),

在这里,失败的条件是:

  1. 如果未填写重复密码字段,则该按钮也将启用
  2. 我只是想显示密码必须匹配的消息,包括两个密码需要匹配并且两个字段都是必需的条件。

在这里,通过上面的这些验证,这些东西不起作用

谁能帮我这个 ?

4

1 回答 1

0
  1. 因为你repeatPassword用 message 验证是空字符串''。因此,如果此字段未填写,errors.repeatPassword则按钮为''disabledfalse

  2. 像这样更新您的代码:

    validationSchema: Yup.object().shape({
      password: Yup.string().required('Password is required'),
      repeatPassword: Yup.string()
        .required('Required')
        .oneOf([Yup.ref('password'), null], 'Passwords must match')
    }),
    

{errors.repeatPassword !== "Required" && <div>{errors.repeatPassword}</div>}

于 2021-04-26T03:28:38.637 回答