Formik: How to prevent validation of pristine fields with schemaValidation?

Created on 18 Oct 2018  路  6Comments  路  Source: formium/formik

鉂換uestion

why does validateOnBlur and validateOnChange run validation on fields that have not been touched yet (pristine fields) per image? In my case I am running validationSchema to check the values. If I turn both of them off, then

screen shot 2018-10-18 at 4 40 28 pm

If I make validateOnBlur and validateOnChange to false then, it doesn't update an error once it has been fixed within the field...

screen shot 2018-10-18 at 4 50 17 pm

Please assist. The code is below.

export enum FormField {
  UsernameOrEmail = 'usernameOrEmail',
  Password = 'password',
}

export const validationSchema = Yup.object().shape({
  [FormField.UsernameOrEmail]: Yup.string().required('Username or Email is required.'),
  [FormField.Password]: Yup.string().required('Password is required.'),
});

const LoginPage: React.SFC<StateProps & DispatchProps> = props => (
  <LayoutForLogin>
    <Container>
      <StyledPelotonLogo fill="#FFF" />
      <Formik
        isInitialValid={false}
        initialValues={{
          [FormField.UsernameOrEmail]: '',
          [FormField.Password]: '',
        }}
        onSubmit={() => (handleSubmit(props.submitLogInForm))}
        component={Form}
        validationSchema={validationSchema}
        validateOnBlur  // tried both true and false
        validateOnChange // tried both true and false
      />
      <CenteredBlock>
        <RegisterText>
          New to Peloton?&nbsp;
          <StyledAnchor href={props.registerUrl}>Sign up now.</StyledAnchor>
        </RegisterText>
      </CenteredBlock>
    </Container>
  </LayoutForLogin>
);

const Form: React.SFC<FormikProps<FormValues>> = ({ status, errors, touched, isSubmitting, handleSubmit, isValid }) => (
  <StyledForm onSubmit={handleSubmit}>
    {status && !isSubmitting &&
    <Toast message={status.message} />}
    <Title>Log in</Title>
    <UiFormGroup>
      <Field
        component={UiField}
        label="Username or Email"
        name={FormField.UsernameOrEmail}
        validateOnBlur
      />
      <Field
        component={UiField}
        label="Password"
        name={FormField.Password}
        type="password"
        validateOnBlur
      />
    </UiFormGroup>
    <StyledLinkContainer>
      <StyledLink to={FORGOT_PASSWORD_ROUTE}>Forgot password?</StyledLink>
    </StyledLinkContainer>
    <LoginButton type="submit" disabled={isSubmitting || !isValid}>Log In</LoginButton>
  </StyledForm>
);
stale

All 6 comments

You can achieve this using Yup's when method. See https://codesandbox.io/s/oqvp75vxxz
I did it by looking up the touched field and then returning notRequired() if not touched.

field.when(fieldPath, (value, schema) => {
     const isTouched = !!getIn(formik.touched, fieldPath);
     return isTouched ? schema : schema.notRequired();
});

I believe this should be built in as it makes total sense not to validate other fields that aren't touched, unless explicitly calling validateForm or firing a submit.

@davemooreuws

where is this line from? what is getIn and how do you pass in formik property to yup?

const isTouched = !!getIn(formik.touched, fieldPath);

@davemooreuws Does your solution validate the form if the user tries to blindly submit an empty form?

@andriy-fuzz
You can import getIn from formik

I wrapped the Formik component in a class component and set a variable on the class to the formikProps returned from the render props, so I can access it in the validation methods.

@troydietz Formik will set all the fields to touched on submit, therefore this will work.

Hola! So here's the deal, between open source and my day job and life and what not, I have a lot to manage, so I use a GitHub bot to automate a few things here and there. This particular GitHub bot is going to mark this as stale because it has not had recent activity for a while. It will be closed if no further activity occurs in a few days. Do not take this personally--seriously--this is a completely automated action. If this is a mistake, just make a comment, DM me, send a carrier pidgeon, or a smoke signal.

ProBot automatically closed this due to inactivity. Holler if this is a mistake, and we'll re-open it.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

giulioambrogi picture giulioambrogi  路  3Comments

ancashoria picture ancashoria  路  3Comments

sibelius picture sibelius  路  3Comments

najisawas picture najisawas  路  3Comments

jaredpalmer picture jaredpalmer  路  3Comments