Skip to content

Instantly share code, notes, and snippets.

@predragnikolic
Created January 25, 2023 12:54
Show Gist options
  • Save predragnikolic/c9e9e789c6d1834819052e4a8409717f to your computer and use it in GitHub Desktop.
Save predragnikolic/c9e9e789c6d1834819052e4a8409717f to your computer and use it in GitHub Desktop.
unique yup fields
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