Skip to content

Commit d475ce8

Browse files
authored
Merge pull request #14499 from Automattic/vkarpov15/gh-14496
types(validation): support function for validator `message` property, and add support for accessing validator `reason`
2 parents bb2eb40 + ec21230 commit d475ce8

File tree

3 files changed

+20
-1
lines changed

3 files changed

+20
-1
lines changed

test/types/schema.test.ts

+17
Original file line numberDiff line numberDiff line change
@@ -1407,3 +1407,20 @@ function gh14235() {
14071407
userSchema.omit<Omit<IUser, 'age'>>(['age']);
14081408
}
14091409

1410+
function gh14496() {
1411+
const schema = new Schema({
1412+
name: {
1413+
type: String
1414+
}
1415+
});
1416+
schema.path('name').validate({
1417+
validator: () => {
1418+
throw new Error('Oops!');
1419+
},
1420+
// `errors['name']` will be "Oops!"
1421+
message: (props) => {
1422+
expectType<Error | undefined>(props.reason);
1423+
return 'test';
1424+
}
1425+
});
1426+
}

types/schematypes.d.ts

+2-1
Original file line numberDiff line numberDiff line change
@@ -193,9 +193,10 @@ declare module 'mongoose' {
193193
}
194194

195195
interface Validator<DocType = any> {
196-
message?: string;
196+
message?: string | ((props: ValidatorProps) => string);
197197
type?: string;
198198
validator?: ValidatorFunction<DocType>;
199+
reason?: Error;
199200
}
200201

201202
type ValidatorFunction<DocType = any> = (this: DocType, value: any, validatorProperties?: Validator) => any;

types/validation.d.ts

+1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ declare module 'mongoose' {
66
path: string;
77
fullPath: string;
88
value: any;
9+
reason?: Error;
910
}
1011

1112
interface ValidatorMessageFn {

0 commit comments

Comments
 (0)