yup: added test validator context

This commit is contained in:
nikita-graf
2018-06-16 02:26:34 +03:00
parent 07dd1e802b
commit f7938c66e4
2 changed files with 26 additions and 2 deletions

12
types/yup/index.d.ts vendored
View File

@@ -54,7 +54,7 @@ export interface Schema<T> {
oneOf(arrayOfValues: any[], message?: string): this;
notOneOf(arrayOfValues: any[], message?: string): this;
when(keys: string | any[], builder: WhenOptions<this>): this;
test(name: string, message: string, test: (value?: any) => boolean | Promise<boolean>, callbackStyleAsync?: boolean): this;
test(name: string, message: string, test: (this: TestContext, value?: any) => boolean | Promise<boolean>, callbackStyleAsync?: boolean): this;
test(options: TestOptions): this;
transform(fn: TransformFunction<this>): this;
}
@@ -161,6 +161,14 @@ export type WhenOptions<T> = WhenOptionsBuilder<T>
| { is: boolean | ((value: any) => boolean), then: any, otherwise: any }
| object;
export interface TestContext {
path: string;
options: ValidateOptions;
parent: any;
schema: Schema<any>;
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<boolean>;
test: (this: TestContext, value: any) => boolean | Promise<boolean>;
/**
* The validation error message

View File

@@ -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;