Validation in formik when multiple fields combined together has to be validated

Asked
Active3 hr before
Viewed126 times

9 Answers

formik
90%

For more information about <Formik validate>, see the API reference.,For more information about <Formik validationSchema>, see the API reference.,There are 2 ways to do form-level validation with Formik:

1 // Synchronous validation2 const validate = (values, props /* only available when using withFormik */) => {3   const errors = {};4 5   if (!values.email) {6     errors.email = 'Required';7   } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) {8     errors.email = 'Invalid email address';9   }10 11   //...12 13   return errors;14 };15 16 // Async Validation17 const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));18 19 const validate = (values, props /* only available when using withFormik */) => {20   return sleep(2000).then(() => {21     const errors = {};22     if (['admin', 'null', 'god'].includes(values.username)) {23       errors.username = 'Nice try';24     }25     // ...26     return errors;27   });28 };
load more v
88%

The formValues variable holds the data the user puts into the input fields.,With the useState hook, we set state variables for the formValues, formErrors and isSubmitting.,handleChange This keeps the inputs in sync with the formValues state and updates the state as the user types.

const SignInForm = () => {
  return (
    <Formik
      initialValues={initialValues}
      validate={validate}
      onSubmit={submitForm}
    >
      {(formik) => {
        const {
          values,
          handleChange,
          handleSubmit,
          errors,
          touched,
          handleBlur,
          isValid,
          dirty
        } = formik;
        return (
            <div className="container">
              <h1>Sign in to continue</h1>
              <form onSubmit={handleSubmit}>
                <div className="form-row">
                  <label htmlFor="email">Email</label>
                  <input
                    type="email"
                    name="email"
                    id="email"
                    value={values.email}
                    onChange={handleChange}
                    onBlur={handleBlur}
                    className={errors.email && touched.email ? 
                    "input-error" : null}
                  />
                  {errors.email && touched.email && (
                    <span className="error">{errors.email}</span>
                  )}
                </div>

                <div className="form-row">
                  <label htmlFor="password">Password</label>
                  <input
                    type="password"
                    name="password"
                    id="password"
                    value={values.password}
                    onChange={handleChange}
                    onBlur={handleBlur}
                    className={errors.password && touched.password ? 
                     "input-error" : null}
                  />
                  {errors.password && touched.password && (
                    <span className="error">{errors.password}</span>
                  )}
                </div>

                <button
                  type="submit"
                  className={dirty && isValid ? "" : "disabled-btn"}
                  disabled={!(dirty && isValid)}>
                  Sign In
                </button>
              </form>
            </div>
        );
      }}
    </Formik>
  );
};
load more v
72%

Formik has an onSubmit function that you can check values and see if there is a filled input and show error based on that and prevent user to submit an empty form ,and of course in Formik render section you have access to values property and you can show an error if values are empty. but I guess it doesn't have the best user experience ,Connect and share knowledge within a single location that is structured and easy to search.

and of course in Formik render section you have access to values property and you can show an error if values are empty. but I guess it doesn't have the best user experience

<Formik
      onSubmit={(values) => {
         //here you can read values object and set your custom error in state and then show to the users.
      }}
    >
{({ handleChange, errors, values, isSubmitting, handleSubmit }) => (
        <Form>
          // you have access values here too.
          ...
        </Form>

65%

<Field validate={(fieldValue, formikBag) => ... } /> I want to have access to formikBag inside of field level validation.,<Field validate={(fieldValue) => ... } /> For now field level validaiton funciton gives us only field value.,Field Field nesting just to have form values inside of second Field validation

<FIeld>
{
({form}) => <FIeld validate={value => form.values.FIELD1} > ...</Field>
}
</Field>
load more v
75%

An initial set of values.,All of these are linked via the field names. Here is how I handle a simple form:,A schema to validate the form via yup

Pretag
 Pretag team - issue, fix, solve, resolve
40%

What is happening here is that we are just adding a validation to the condition, so there is really no need to request anything for the validation to happen after everything is constructed already. Due to the flexibility and programmatic nature of Yup it can't distinguish between those two cases.,Fields that depend on each other to be validated need to sorted so they are "constructed" in the correct order, e.g. if depend on field A in field B, you needs to cast and coerce the value in field A before it's handed to B.,Hey guys, let's get straight to the point, I'll show you how to Yup validate two fields that depend on each other.

const yup = require('yup')
const {
   setLocale
} = yup

setLocale({
   mixed: {
      notType: 'the ${path} is obligatory',
      required: 'the field ${path} is obligatory',
      oneOf: 'the field ${path} must have one of the following values: ${values}'
   }
})

const myNameSchema = yup.object().shape({
   first_name: yup.string().ensure().when('surname', {
      is: '',
      then: yup.string().required()
   }),
   surname: yup.string().ensure().when('first_name', {
      is: '',
      then: yup.string().required()
   })
})

[...]
load more v
22%

Formik is a forms library created by Jared Palmer, who was motivated to make using forms in React less manual.,With Formik, you are able to set up an initial form state, validate at the form level, validate at the field level, and render whatever form elements you need.,Validating React-Bootstrap Forms with Formik

1 yarn add formik
2 #or
3n pm i--save formik
load more v
60%

We can pass another value to our useFormik hook called validate. It is a function that accepts values object and returns an errors object. As per docs,,What is Yup? Yup is a JavaScript object schema validator and object parser. Let’s plug-in Yup with Formik.,Formik will validate after each keystroke (change event), each input’s blur event, as well as prior to submission. It will only proceed with executing the onSubmit function we passed to useFormik() if there are no errors (i.e. if our validation function returned {}).

Let’s first install Formik.

npm install formik // oryarn formik
load more v
48%

Introduces field-level validation functions and demonstrates how to display errors next to fields using child render functions.,Introduces a whole-record validation function and demonstrates how to display errors next to fields using child render functions.,Demonstrates how easy it is to use third party input components. All the third party component really needs is value and onChange, but more complex components can accept things like errors.

Pretag
 Pretag team - issue, fix, solve, resolve

Other "formik-undefined" queries related to "Validation in formik when multiple fields combined together has to be validated"