React validation

React form validation

Challenge

  • Reuse validation rules, how much flexibility, to compose rules, declarative way and

  • Dependencies, from redux, window, (Parent) Components, form state, react-context

  • When to run validation, onChange, onBlur, onSubmit, imperative manual trigger will cause nightmare

  • Async validation, needed to be cancellable

  • Dirty/touch check is validations is declarative and run on every fields (which is good)

Common practice

Form-level Validation

Complete access to all form state and props whenever the function runs, so you can validate dependent fields at the same time.

validationContext can be passed and handled from the same level (top-level)

I. Formik:

<Formik validate={fn}> and withFormik({ validate: fn }), fn as (formInfo) => errors

<Formik validationSchema={yupSchema}> and withFormik({ validationSchema: yupSchema })

II.React-Hook-Form:

const { register, handleSubmit, errors } = useForm({
    validationResolver: resolver,
    /*
    resolver as (data, context) => errors;
    */
    validationContext: { test: "test" }
  });

etc.

Yup is awesome

Field-level validation

I. Formik: <Field component={Input} name="name" validation={validationFn}>

Ref: https://jaredpalmer.com/formik/docs/guides/validation

II. React-Hook-Form:

<Controller as={TextField} name="TextField" control={control} defaultValue="" rule={validationObject}/>

or

<input ref={register(ValidationObject)} name="Name"/>

etc.

Another approach validation

A list of validation rules:

validation id binds to i18n, rule, seems easy while hard for compose and plug.

For rules based logic, consider boolean algebra, and using correct AND, OR, XOR rules:

validationsToTrigger for onChange event, validationsToClear for Priority overwrite. validationsToClear can be used for each validation rules, or fields

Hand pick rule for Component onChange.

Last updated