yup validation on multiple values

bunny picture bunny · Sep 10, 2019 · Viewed 25k times · Source

I want to validate my form using yup in formik. Suppose I have 4 fields A, B, C, D and they are all strings. How should I write the validation schema if I want to have at least one of the fields is not empty, then that's a valid form? Thanks in advance!

Answer

Jamie Shepherd picture Jamie Shepherd · Sep 10, 2019

When using Yup if all normal features fail you, you can use the .test feature, documented here - https://github.com/jquense/yup#mixedtestname-string-message-string--function-test-function-schema

mixed.test(name: string, message: string | function, test: function): Schema

Adds a test function to the validation chain. Tests are run after any object is cast. Many types have some tests built in, but you can create custom ones easily. In order to allow asynchronous custom validations all (or no) tests are run asynchronously. A consequence of this is that test execution order cannot be guaranteed.

For your implementation you will want to write a "test" for each of your 4 fields to make sure one of the 4 are not null.

field1: yup
    .string()
    .test(
      'oneOfRequired',
      'One of Field1, Field2, Field3 or Field4 must be entered',
      function(item) {
        return (this.parent.field1 || this.parent.field2 || this.parent.field3 || this.parent.field4)
      }
    ),
field2: yup
    .string()
    .test(
      'oneOfRequired',
      'One of Field1, Field2, Field3 or Field4 must be entered',
      function(item) {
        return (this.parent.field1 || this.parent.field2 || this.parent.field3 || this.parent.field4)
      }
    ),

etc...

Please note in this case I have not used an arrow function. This is because to use the 'this' context you must use this syntax, this is mentioned in the Yup documentation.