[yup] Add ValidationError as a valid return type for the test function

This commit is contained in:
Dražen Tenžera
2018-08-15 14:16:09 +02:00
parent 21487e4d9e
commit 73095f3f18
2 changed files with 22 additions and 2 deletions

View File

@@ -55,7 +55,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: (this: TestContext, value?: any) => boolean | Promise<boolean>, callbackStyleAsync?: boolean): this;
test(name: string, message: string, test: (this: TestContext, value?: any) => boolean | ValidationError | Promise<boolean | ValidationError>, callbackStyleAsync?: boolean): this;
test(options: TestOptions): this;
transform(fn: TransformFunction<this>): this;
}
@@ -202,7 +202,7 @@ export interface TestOptions {
/**
* Test function, determines schema validity
*/
test: (this: TestContext, value: any) => boolean | Promise<boolean>;
test: (this: TestContext, value: any) => boolean | ValidationError | Promise<boolean | ValidationError>;
/**
* The validation error message

View File

@@ -141,6 +141,26 @@ mixed.test({
test: testContext
});
// Async ValidationError
const asyncValidationErrorTest = function(this: TestContext): Promise<ValidationError> {
return new Promise(resolve => resolve(this.createError({ path: "testPath", message: "testMessage" })));
};
mixed.test('async-validation-error', 'Returns async ValidationError', asyncValidationErrorTest);
mixed.test({
test: asyncValidationErrorTest,
});
// Sync ValidationError
const syncValidationErrorTest = function(this: TestContext): ValidationError {
return this.createError({ path: "testPath", message: "testMessage" });
};
mixed.test('sync-validation-error', 'Returns sync ValidationError', syncValidationErrorTest);
mixed.test({
test: syncValidationErrorTest,
});
yup.string().transform(function(this, value: any, originalvalue: any) {
return this.isType(value) && value !== null ? value.toUpperCase() : value;
});