仅在触摸字段时如何显示错误? | React && Formik

时间:2019-02-06 12:04:14

标签: javascript reactjs forms validation formik

我有一个用React和Formik制作的表格。除了一个极端的情况外,一切工作都很好。如果未触摸到电子邮件,则需要隐藏错误消息(About wrong email address),因为它不是必需的。

问题: 用户邮件是必需的,即使它是完全不相关的错误。

我尝试在条件渲染内将字段设置为touch,因此,仅在触摸该字段时才会出现错误。如下所示:

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部分中也对其进行了设置。 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地址。如果我尝试提交但未提供电子邮件地址,则错误不会出现。

当前结果: 错误出现,并且不允许我提交。

1 个答案:

答案 0 :(得分:1)

您只能用yup来做。您不需要其他自定义验证

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

是的,请在填写电子邮件时对其进行验证,并允许使用空白的电子邮件字段提交表单