How to validate a field onBlur and other field onChange using Formik?

Viewed 3096

I have a form with an email input and a password input. I'm using formik with react and I need to validate the email input onBlur only and validate password on change after first submit.

For now, what I have is that validation will run on Blur until something is touched (handleValidate will run and set validationAttempt to true and the prop validateOnChange is equal to validationAttempt), then it will validate onChange. But I get the same behavior for all the fields and can't give each field a different behavior.

How can I achieve this??

const [validationAttempt, setValidationAttempt] = React.useState(false);

const handleValidate = values => {
    const errors = {};
    const fields = Object.keys(values);
    setValidationAttempt(true);

    fields.forEach(field => {
      if (values[field] === "") {
        errors[field] = `This field is mandatory`;
        return;
      }
      if (field === "email") {
        if (!values[field].includes("@")) {
          errors[field] = `Must use "@" `;
        }
        if (!values[field].includes(".com")) {
          errors[field] = `Must use ".com" `;
        }
      }
      if (field === "password") {
        setValidationAttempt(true);
        if (values[field].length < 8) {
          errors[field] = `Must be greater than 8 characters`;
        }
      }
    });
    return errors;
  };


    <Formik
                      initialValues={{
                        email: "",
                        password: "",
                      }}
                      validate={values => handleValidate(values)}
                      validateOnChange={validationAttempt}
                      validateOnBlur
                      onSubmit={(
                        {
                          email,
                          password,
                        }
                      ) => {submit(email, password)}}
                    >
                      {({
                        handleChange,
                        handleSubmit,
                        handleBlur,
                        values,
                        errors,
                        touched,
                      }) => {
                        return (
                          <>
                            <div className="registerContainer">
                              <div className="registerContainer__row">
                                <TextField
                                  name="password"
                                  errors={errors}
                                  touched={touched}
                                  fieldname="password"
                                  autoComplete="password"
                                  label={intl.formatMessage(
                                    commonMessages.password
                                  )}
                                  onBlur={handleBlur}
                                  onChange={handleChange}
                                  value={values.password}
                                  className=" input__field"
                                />
    
                                <TextField
                                  className="input__field"
                                  fieldname="email"
                                  errors={errors}
                                  touched={touched}
                                  name="email"
                                  autoComplete="email"
                                  label={intl.formatMessage(
                                    commonMessages.email
                                  )}
                                  type="email"
                                  onBlur={handleBlur}
                                  onChange={handleChange}
                                  value={values.email}
                                />
                              </div>
                              <Button onClick={handlSubmit} />
                            </div>
    }
    </Formik>
1 Answers

with ANGULAR !!!! Here is an example (when creating the form group in ts file).

>     this.passwordUpdateForm = this.formBuilder.group(
>       {
>         oldPassword: new FormControl('', { validators: [Validators.required, Validators.pattern(this.oldPassword)], updateOn:
> 'change' }),
>         newPassword: new FormControl('', {
>           validators: [Validators.required, Validators.minLength(5), this.credentialsValidator.differentThanValidator(this.oldPassword)],
>           updateOn: 'change',
>         }),
>         retypedNewPassword: new FormControl('', {
>           validators: [Validators.required, Validators.minLength(5)],
>           updateOn: 'blur',
>         }),
>       },
>     );
Related