From 3ea35bfbe5f5d2cf90d00910b8c6e1bae72cd5e2 Mon Sep 17 00:00:00 2001 From: Adrien MILLE Date: Wed, 14 Apr 2021 16:07:09 +0800 Subject: [PATCH] feat: add the only validator --- docs/validators.md | 13 ++++++++++++- src/OnlyValidator.ts | 26 ++++++++++++++++++++++++++ src/methods.ts | 1 + src/validators.ts | 4 ++++ 4 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 src/OnlyValidator.ts diff --git a/docs/validators.md b/docs/validators.md index b547645..962e916 100644 --- a/docs/validators.md +++ b/docs/validators.md @@ -83,5 +83,16 @@ validator.custom( return null; }, -) +); +``` + +## only + +The only validator allow you to make a validator optional based on a condition. + +```js +validators.only( + (values, errors, context) => values?.answer === 42, + validators.requiredString('anotherValue'), +); ``` diff --git a/src/OnlyValidator.ts b/src/OnlyValidator.ts new file mode 100644 index 0000000..99eb087 --- /dev/null +++ b/src/OnlyValidator.ts @@ -0,0 +1,26 @@ +import Context from './Context'; +import Validator from './Validator'; + +export type OnlyChecker = (values: any, errors: any, context: Context) => boolean; + +class OnlyValidator extends Validator { + protected check: OnlyChecker; + + protected validator: Validator; + + constructor(check: OnlyChecker, validator: Validator) { + super(); + this.validator = validator; + this.check = check; + } + + public execute(values: any, errors: any, context: Context): any { + if (this.check(values, errors, context)) { + return this.validator.execute(values, errors, context); + } + + return errors; + } +} + +export default OnlyValidator; diff --git a/src/methods.ts b/src/methods.ts index c756517..e95df5f 100644 --- a/src/methods.ts +++ b/src/methods.ts @@ -6,3 +6,4 @@ export { default as RequiredNumber } from './RequiredNumber'; export { default as RequiredString } from './RequiredString'; export { default as RequiredValue } from './RequiredValue'; export { default as CustomValidator } from './CustomValidator'; +export { default as OnlyValidator } from './OnlyValidator'; diff --git a/src/validators.ts b/src/validators.ts index 9fe8a56..4ce714c 100644 --- a/src/validators.ts +++ b/src/validators.ts @@ -1,5 +1,6 @@ import { PropertyPath } from 'lodash'; import { CustomValidatorHandler } from './CustomValidator'; +import { OnlyChecker } from './OnlyValidator'; import Validator from './Validator'; import * as methods from './methods'; @@ -26,3 +27,6 @@ export const forEach = (field: PropertyPath, validator: Val export const custom = (field: PropertyPath, validator: CustomValidatorHandler) => new methods.CustomValidator(field, validator); + +export const only = (check: OnlyChecker, validator: Validator) => + new methods.OnlyValidator(check, validator);