Sidney  Purdy

Sidney Purdy

1593513911

Use Yup with Redux-form

I wanted to replace Joiand Redux-Form with [Yup](https://github.com/jquense/yup)and [Formik](https://github.com/jaredpalmer/formik), respectively. “Now why would you want to do that!?”, you might ask. Well let’s quickly go through the reasons for Yup and Formik.

Why Yup

  1. Much lightweight than Joi.

And this is why ‘lightweight’ is important:

_tl;dr: less code = less parse/compile + less transfer + less to decompress _source

2. Easier to parse for error messages from returned error object.

3. Much flexible to customize error messages without string manipulation shenanigans.

4. Yup shares very much similar syntax and method names with Joi, making replacing Joi an easy task.

Why Formik

See “Why not Redux-Form?


However, replacing redux-form with Formik was considered to me to be a heavier task than Joi with Yup, therefore here goes ‘your friendly’ medium article about it — the gist of making Yup plays well with redux-form.

First we create a validator function that will accepts our Yup schema later.

import { Schema } from 'yup';

const validator = <T>(schema: Schema<T>) => async formValues => {
  try {
    await schema.validate(formValues, { abortEarly: false })
    return {}
  } catch (errors) {
    return errors.inner.reduce(
      (errors, err) => ({
        ...errors,
        [err.path]: err.message
      }),
      {}
    )
  }
}

export default validator

#yup #redux-form-yup #react #redux-form #programming #redux

Use Yup with Redux-form