From ec212309f666fc04276d40c921090bea5b5d0e37 Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Thu, 4 Apr 2024 14:39:24 -0400 Subject: [PATCH] types(validation): support function for validator `message` property, and add support for accessing validator `reason` Fix #14496 --- test/types/schema.test.ts | 17 +++++++++++++++++ types/schematypes.d.ts | 3 ++- types/validation.d.ts | 1 + 3 files changed, 20 insertions(+), 1 deletion(-) diff --git a/test/types/schema.test.ts b/test/types/schema.test.ts index e7631229036..de80dc0de73 100644 --- a/test/types/schema.test.ts +++ b/test/types/schema.test.ts @@ -1407,3 +1407,20 @@ function gh14235() { userSchema.omit>(['age']); } +function gh14496() { + const schema = new Schema({ + name: { + type: String + } + }); + schema.path('name').validate({ + validator: () => { + throw new Error('Oops!'); + }, + // `errors['name']` will be "Oops!" + message: (props) => { + expectType(props.reason); + return 'test'; + } + }); +} diff --git a/types/schematypes.d.ts b/types/schematypes.d.ts index 9cb48343009..778b83c7ad5 100644 --- a/types/schematypes.d.ts +++ b/types/schematypes.d.ts @@ -193,9 +193,10 @@ declare module 'mongoose' { } interface Validator { - message?: string; + message?: string | ((props: ValidatorProps) => string); type?: string; validator?: ValidatorFunction; + reason?: Error; } type ValidatorFunction = (this: DocType, value: any, validatorProperties?: Validator) => any; diff --git a/types/validation.d.ts b/types/validation.d.ts index 693261250e7..488ead7e588 100644 --- a/types/validation.d.ts +++ b/types/validation.d.ts @@ -6,6 +6,7 @@ declare module 'mongoose' { path: string; fullPath: string; value: any; + reason?: Error; } interface ValidatorMessageFn {