From f7938c66e492c2b020105fcef43731d3c29a7169 Mon Sep 17 00:00:00 2001 From: nikita-graf Date: Sat, 16 Jun 2018 02:26:34 +0300 Subject: [PATCH] yup: added test validator context --- types/yup/index.d.ts | 12 ++++++++++-- types/yup/yup-tests.ts | 16 ++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/types/yup/index.d.ts b/types/yup/index.d.ts index 243cb985c1..08697521d8 100644 --- a/types/yup/index.d.ts +++ b/types/yup/index.d.ts @@ -54,7 +54,7 @@ export interface Schema { oneOf(arrayOfValues: any[], message?: string): this; notOneOf(arrayOfValues: any[], message?: string): this; when(keys: string | any[], builder: WhenOptions): this; - test(name: string, message: string, test: (value?: any) => boolean | Promise, callbackStyleAsync?: boolean): this; + test(name: string, message: string, test: (this: TestContext, value?: any) => boolean | Promise, callbackStyleAsync?: boolean): this; test(options: TestOptions): this; transform(fn: TransformFunction): this; } @@ -161,6 +161,14 @@ export type WhenOptions = WhenOptionsBuilder | { is: boolean | ((value: any) => boolean), then: any, otherwise: any } | object; +export interface TestContext { + path: string; + options: ValidateOptions; + parent: any; + schema: Schema; + createError: (params: { path: string, message: string }) => ValidationError; +} + export interface ValidateOptions { /** * Only validate the input, and skip and coercion or transformation. Default - false @@ -193,7 +201,7 @@ export interface TestOptions { /** * Test function, determines schema validity */ - test: (value: any) => boolean | Promise; + test: (this: TestContext, value: any) => boolean | Promise; /** * The validation error message diff --git a/types/yup/yup-tests.ts b/types/yup/yup-tests.ts index 871df0e8e0..d753d0af9b 100644 --- a/types/yup/yup-tests.ts +++ b/types/yup/yup-tests.ts @@ -124,6 +124,22 @@ mixed.test({ test: value => value == null || value.length <= 5 }); mixed.test('with-promise', 'It contains invalid value', value => new Promise(resolve => true)); +mixed.test('with-context', 'it uses function context', function() { + this.options.context; + this.path; + this.createError({ path: '1', message: '1' }); + this.schema.meta(); + return true; +}); +mixed.test({ + test() { + this.options.context; + this.path; + this.createError({ path: '1', message: '1' }); + this.schema.meta(); + return true; + } +}); yup.string().transform(function(this, value: any, originalvalue: any) { return this.isType(value) && value !== null ? value.toUpperCase() : value;