Last active
December 7, 2023 10:27
-
-
Save klaasvw/746756ba451dcf99adb2aa3ecbb033bd to your computer and use it in GitHub Desktop.
Yup validation based on other data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as Yup from 'yup'; | |
import type { MyType } from 'my-types-package'; | |
import { MyOtherSchema } from 'kotk-vdb'; | |
export const MySchema = ( | |
otherData: MyType, | |
otherValidatorFn: (value: string, dataId: string) => Promise<boolean> | |
) => { | |
return { | |
simpleSelect: Yup.string() | |
.required('Select a valid value') | |
.oneOf(['a', 'b', 'c']), | |
externalValidator: Yup.string() | |
.when('otherField', { | |
is: 'otherFieldValue', | |
then: (schema) => schema | |
.min(3, 'Minimum 3 characters') | |
.max(100, 'Max 100 characters') | |
.required('The field is required') | |
.test('otherValidatorFn', 'Invalid value.', async (value) => { | |
return await otherValidatorFn(value, otherData.id) | |
}), | |
}), | |
...MyOtherSchema, | |
otherDataBasedValue: Yup.boolean() | |
.when('otherValue', { | |
is: (value) => value != otherData.otherValue, | |
then: (schema) => schema.test('isFalse', 'Cannot be false', (value) => !value), | |
}), | |
otherFormData: Yup.string() | |
// Because we rely on parent data in the form we use a test instead of | |
// "when", because the other field may not be present in the data passed | |
// to this schema. | |
.test('isRequired', 'Error message', function (value, context) { | |
if (context?.parent?.otherFormField !== undefined && context?.parent?.otherFormField !== 'value' ) { | |
return value === '1' || value === '0'; | |
} | |
return true; | |
}), | |
otherNestedFormData: Yup.string() | |
// As above, but in this case the parent is also nested. | |
.test('isRequired', 'Error message', function (value, context) { | |
// If parent is also nested | |
const rootCtx = context?.from?.[context?.from?.length - 1]?.value; | |
return true; | |
}), | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment