David Moll
David Moll

Reputation: 129

Reusing Yup-validations on different values

I have a form which needs validation where each row (with 4 elements each) is optional unless a single one is filled out. While this validation is all working it led to a lot of repitition since I have 5 rows, equalling almost 150 lines of repeating code:

    var1: Yup.date().when(['var2', 'var3', 'var4'], {
        is: (a: string, b: number, c: File) =>
            a !== undefined || b !== undefined || c !== undefined,
        then: Yup.date().required('Please fill out var1'),
    }),
var2: Yup.string().when(['var1', 'var3', 'var4'], {
        is: (a: Date, b: number, c: File) =>
            a !== undefined || b !== undefined || c !== undefined,
        then: Yup.string().required('Please fill out var2'),
    }),
var3: Yup.string().when(['var1', 'var2', 'var4'], {
        is: (a: Date, b: number, c: File) =>
            a !== undefined || b !== undefined || c !== undefined,
        then: Yup.string().required('Please fill out var3'),
    }),
var4: Yup.mixed()
        .when(['var1', 'var2', 'var3'], {
            is: (a: Date, b: string, c: number) =>
                a !== undefined || b !== undefined || c !== undefined,
            then: Yup.mixed().required('Please fill out var4'),
    })

//Here the repition starts

var5: Yup.date().when(['var6', 'var7', 'var8'], {
        is: (a: string, b: number, c: File) =>
            a !== undefined || b !== undefined || c !== undefined,
        then: Yup.date().required('Please fill out var5'),
    }),
var6: Yup.string().when(['var5', 'var7', 'var8'], {
        is: (a: Date, b: number, c: File) =>
            a !== undefined || b !== undefined || c !== undefined,
        then: Yup.string().required('Please fill out var6'),
    }),
var7: Yup.string().when(['var5', 'var6', 'var8'], {
        is: (a: Date, b: number, c: File) =>
            a !== undefined || b !== undefined || c !== undefined,
        then: Yup.string().required('Please fill out var7'),
    }),
var8: Yup.mixed()
        .when(['var5', 'var6', 'var7'], {
            is: (a: Date, b: string, c: number) =>
                a !== undefined || b !== undefined || c !== undefined,
            then: Yup.mixed().required('Please fill out var8'),
    })

Is there a possibility of reusing those blocks, maybe in a function and Yup.test or am I stuck with those blocks?

Upvotes: 0

Views: 403

Answers (1)

Mariya
Mariya

Reputation: 21

You may refactor like the next code example:

    const checkCondition = (a: string, b: number, c: File) =>
        return a !== undefined || b !== undefined || c !== undefined;

then use a function:

      var5: Yup.date().when(['var6', 'var7', 'var8'], {
            is: checkCondition(a, b, c),
            then: Yup.date().required('Please fill out var5'),
        }),

All similar functions you may put to utils.tsx/.js file and just import/export.

Upvotes: 2

Related Questions