3
votes

I have a form made with React and Formik. Everything works just fine, except for one edge case scenario. I need to hide the error message(About wrong email address) for the email input if it is not touched as it is not required.

THE PROBLEM: The user thinks email is required, even if it is a completely unrelated error.

I have tried setting the field to touch, inside the conditional render, so, the error appears only when the field is being touched. Like below:

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

That doesn't work. I have it set on touched also in the JSX portion of the code. 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;

Expected Results: Show the Invalid Email Address only, when the field has been touched. If I try to submit and I haven't provided an email address, the error should not appear.

Current Results: The error appears and doesn't let me submit.

1

1 Answers

3
votes

You can do it with yup only. You dont need additional custom validation

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

Yup validate it when email filled and allow submit form with empty email field