-
Notifications
You must be signed in to change notification settings - Fork 22
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
59 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
import { | ||
Maybe, | ||
AnyObject, | ||
InferType, | ||
ValidateOptions, | ||
ValidationError, | ||
ObjectSchema | ||
} from 'yup'; | ||
|
||
export function tryValidateSync< | ||
T extends Maybe<AnyObject>, | ||
Schema extends ObjectSchema<T> | ||
>( | ||
value: T, | ||
schema: Schema, | ||
kwArgs?: { | ||
options?: ValidateOptions | ||
} | ||
): InferType<Schema> | undefined; | ||
|
||
export function tryValidateSync< | ||
T extends Maybe<AnyObject>, | ||
Schema extends ObjectSchema<T>, | ||
OnErrorRT extends InferType<Schema> | void | ||
>( | ||
value: T, | ||
schema: Schema, | ||
kwArgs?: { | ||
options?: ValidateOptions, | ||
onError: (error: ValidationError) => OnErrorRT | ||
} | ||
): OnErrorRT extends InferType<Schema> | ||
? InferType<Schema> | ||
: InferType<Schema> | undefined; | ||
|
||
export function tryValidateSync< | ||
T extends Maybe<AnyObject>, | ||
Schema extends ObjectSchema<T>, | ||
OnErrorRT extends InferType<Schema> | void | ||
>( | ||
value: T, | ||
schema: Schema, | ||
kwArgs?: { | ||
options?: ValidateOptions, | ||
onError?: (error: ValidationError) => OnErrorRT | ||
} | ||
): InferType<Schema> | undefined { | ||
try { | ||
return schema.validateSync(value, kwArgs?.options); | ||
} catch (error) { | ||
if (!(error instanceof ValidationError)) { | ||
throw error; | ||
} else if (kwArgs?.onError !== undefined) { | ||
return kwArgs.onError(error) as InferType<Schema> | undefined; | ||
} | ||
} | ||
|
||
return undefined; | ||
} |