Skip to content

Commit

Permalink
Merge pull request #14499 from Automattic/vkarpov15/gh-14496
Browse files Browse the repository at this point in the history
types(validation): support function for validator `message` property,  and add support for accessing validator `reason`
  • Loading branch information
vkarpov15 committed Apr 7, 2024
2 parents bb2eb40 + ec21230 commit d475ce8
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 d475ce8

Please sign in to comment.