如何仅在触摸 Field 时显示错误? |反应 && 福尔米克

How to show error only if Field is touched? | React && Formik

我有一个用 React 和 Formik 制作的表格。一切正常,除了一种极端情况。我需要隐藏电子邮件输入的错误消息(About wrong email address),如果它没有被触摸,因为它不是必需的。

问题: 用户认为电子邮件是必需的,即使这是一个完全不相关的错误。

我已经尝试在条件渲染中将字段设置为触摸,因此,只有在触摸字段时才会出现错误。如下所示:

const emailValidation = (value, field) => {
  let emailErrorMessage;
  if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(value) && field.email.touched) {
    emailErrorMessage = 'Invalid email address';
  }
  return emailErrorMessage;
};

那是行不通的。我在代码的 JSX 部分也将其设置为 touched 。 See below:

const createUserValidationSchema = Yup.object().shape({
  username: Yup.string('Provide a Username').required('Username is Required'),
  email: Yup.string('Provide an email'),
  password: Yup.string('Enter your password').required('Password is Required'),
  confirmPassword: Yup.string('Enter your password again')
    .required('Password Confirmation is Required')
    .oneOf([Yup.ref('password')], 'Passwords do not match')
});

const emailValidation = (value, field) => {
  let emailErrorMessage;
  if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(value) && field.email.touched) {
    emailErrorMessage = 'Invalid email address';
  }
  return emailErrorMessage;
};

class userValidation extends Component {
  static propTypes = {
    ...formPropTypes,
    username: PropTypes.string,
    email: PropTypes.string,
    password: PropTypes.string,
    confirmPassword: PropTypes.string,
    groupSelect: PropTypes.func
  };

  static defaultProps = {
    email: ''
  };

  state = {
    type: 'password',
  };

 render() {
    const { type } = this.state;
    return (
      <div className="col-8">
        <h3>Create User</h3>
        <Formik
          initialValues={{
            username: '',
            email: '',
            password: '',
            confirmPassword: ''
          }}
          validationSchema={createUserValidationSchema}
          onSubmit={values => {
            // same shape as initial values
            console.log(values);
          }}
        >
          {({ errors, touched }) => (
            <Form>
              <div className="my-3">
                <label>
                  Username <span className="text-danger">*</span>
                </label>
                <Field name="username" type="text" className="form-control rounded-0" />
                {errors.username && touched.username ? (
                  <div className="text-danger">{errors.username}</div>
                ) : null}
              </div>
              <div className="my-3">
                <label>email</label>
                <Field
                  name="email"
                  validate={emailValidation}
                  type="email"
                  className="form-control rounded-0"
                />
                {errors.email && touched.email ? (
                  <div className="text-danger">{errors.email}</div>
                ) : null}
              </div>
              <div className="my-3">
                <label>
                  Password <span className="text-danger">*</span>
                </label>
                <div className="d-flex align-items-center">
                  <Field type={type} name="password" className="form-control rounded-0 mr-2" />
                  <span
                    className={type === 'password' ? 'fa fa-eye fa-lg' : 'fa fa-eye-slash fa-lg'}
                    onClick={this.togglePasswordMask}
                  />
                </div>
                {errors.password && touched.password ? (
                  <div className="text-danger">{errors.password}</div>
                ) : null}
              </div>
              <div className="my-3">
                <label>
                  Confirm Password <span className="text-danger">*</span>
                </label>
                <Field name="confirmPassword" type={type} className="form-control rounded-0" />
                {errors.confirmPassword && touched.confirmPassword ? (
                  <div className="text-danger">{errors.confirmPassword}</div>
                ) : null}
              </div>
              <button type="submit" className="btn btn-primary rounded-0 float-right my-3">
                Create User
              </button>
            </Form>
          )}
        </Formik>
      </div>
    );
  }
}

export default userValidation;

预期结果: 仅在触摸该字段时显示 Invalid Email 地址。如果我尝试提交但没有提供电子邮件地址,则不会出现错误。

当前结果: 出现错误,不让我提交。

你只能用是的。您不需要额外的自定义验证

const createUserValidationSchema = Yup.object().shape({
  email: Yup.string().email('Provide an email'),
  ....
});

是的,当电子邮件填写时验证它并允许提交带有空电子邮件字段的表单