Created
January 25, 2023 12:54
-
-
Save predragnikolic/c9e9e789c6d1834819052e4a8409717f to your computer and use it in GitHub Desktop.
unique yup fields
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 { ObjectShape } from 'yup/lib/object' | |
declare module 'yup' { | |
interface ObjectSchema<TShape extends ObjectShape> { | |
unique(uniqueKey: string, message: string): ObjectSchema<TShape>; | |
} | |
} | |
Yup.addMethod(Yup.object, 'unique', function (uniqueKey: string, errorMessage: string) { | |
return this.test('unique', { [uniqueKey]: errorMessage }, function (object) { | |
if (!Array.isArray(this.parent)) { | |
throw new Error('unique requires the parrent to be an array') | |
} | |
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access | |
const nonUniqueItems = this.parent.filter((item: any) => item[uniqueKey] === object[uniqueKey]) | |
// return false to show the error message | |
// it is valid only if one item exist in nonUniqueItems | |
return nonUniqueItems.length === 1 | |
}) | |
}) | |
export const userSchema = Yup.object().shape({ | |
formValues: Yup.array().of( | |
Yup.object().shape({ | |
name: Yup.string() | |
.min(3, 'errors.shortname') | |
.required('errors.required'), | |
email: Yup.string() | |
.email('errors.email') | |
.required('errors.required'), | |
}).unique('email', 'Duplicate email address') | |
) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment