Search code examples
reactjsformikyup

Yup dynamic object validation


I am sending a value to yupa via formik. As a result of this value, what can I do to make the necessary checks and return an error message in this style? Since the object has unlimited length, I decided to keep it validated as an object in order not to cause any slowness. I'm solving it with array but the yup part is getting slow.

The body I send:

{
  user_id_1: {
    name: 'test name', // required
    surname: 'test surname', // required
    age: 10, // optional
  },
  user_id_2: {
    name: 'test name 2',
    surname: 'test surname 2',
  },
  user_id_3: {
    name: 'test name 2',
    surname: '',
  },
}

The expected error result:

user_id_3: {
    surname: 'surname is required',
},

Solution

  • I wrote and tested a code suitable for my question. I want to share the solution with you. The critical point here was that I produced my own method and a custom error message with addMethod. You can check how I did it in the related code example. The inside of the test could be solved with the yup scheme, but I solved it at a simple level with if else. The else part in the test is also important, if I do not delete the object value, it remains in the cache.

    code example: codesandbox