Skip to content

Commit

Permalink
feat: add the only validator
Browse files Browse the repository at this point in the history
  • Loading branch information
amille44420 committed Apr 14, 2021
1 parent c4da25b commit 3ea35bf
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 1 deletion.
13 changes: 12 additions & 1 deletion docs/validators.md
Original file line number Diff line number Diff line change
Expand Up @@ -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'),
);
```
26 changes: 26 additions & 0 deletions src/OnlyValidator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import Context from './Context';
import Validator from './Validator';

export type OnlyChecker<TOuterContext> = (values: any, errors: any, context: Context<TOuterContext>) => boolean;

class OnlyValidator<TOuterContext = any> extends Validator<TOuterContext> {
protected check: OnlyChecker<TOuterContext>;

protected validator: Validator<TOuterContext>;

constructor(check: OnlyChecker<TOuterContext>, validator: Validator<TOuterContext>) {
super();
this.validator = validator;
this.check = check;
}

public execute(values: any, errors: any, context: Context<TOuterContext>): any {
if (this.check(values, errors, context)) {
return this.validator.execute(values, errors, context);
}

return errors;
}
}

export default OnlyValidator;
1 change: 1 addition & 0 deletions src/methods.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
4 changes: 4 additions & 0 deletions src/validators.ts
Original file line number Diff line number Diff line change
@@ -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';

Expand All @@ -26,3 +27,6 @@ export const forEach = <TOuterContext = any>(field: PropertyPath, validator: Val

export const custom = <TOuterContext = any>(field: PropertyPath, validator: CustomValidatorHandler<TOuterContext>) =>
new methods.CustomValidator<TOuterContext>(field, validator);

export const only = <TOuterContext = any>(check: OnlyChecker<TOuterContext>, validator: Validator<TOuterContext>) =>
new methods.OnlyValidator<TOuterContext>(check, validator);

0 comments on commit 3ea35bf

Please sign in to comment.