Skip to content

Commit

Permalink
types(validation): support function for validator message property,…
Browse files Browse the repository at this point in the history
… and add support for accessing validator `reason`

Fix #14496
  • Loading branch information
vkarpov15 committed Apr 4, 2024
1 parent 4ea42d2 commit ec21230
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 1 deletion.
17 changes: 17 additions & 0 deletions test/types/schema.test.ts
Expand Up @@ -1407,3 +1407,20 @@ function gh14235() {
userSchema.omit<Omit<IUser, 'age'>>(['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<Error | undefined>(props.reason);
return 'test';
}
});
}
3 changes: 2 additions & 1 deletion types/schematypes.d.ts
Expand Up @@ -193,9 +193,10 @@ declare module 'mongoose' {
}

interface Validator<DocType = any> {
message?: string;
message?: string | ((props: ValidatorProps) => string);
type?: string;
validator?: ValidatorFunction<DocType>;
reason?: Error;
}

type ValidatorFunction<DocType = any> = (this: DocType, value: any, validatorProperties?: Validator) => any;
Expand Down
1 change: 1 addition & 0 deletions types/validation.d.ts
Expand Up @@ -6,6 +6,7 @@ declare module 'mongoose' {
path: string;
fullPath: string;
value: any;
reason?: Error;
}

interface ValidatorMessageFn {
Expand Down

0 comments on commit ec21230

Please sign in to comment.