Skip to content

Commit

Permalink
feat: added parameters to the generic rule class to pass the whole fo…
Browse files Browse the repository at this point in the history
…rm to the validator
  • Loading branch information
ziccardi committed Oct 2, 2020
1 parent 432b354 commit abd9813
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -60,4 +60,4 @@
"type": "git",
"url": "git://github.com/ziccardi/json-data-validator.git"
}
}
}
19 changes: 16 additions & 3 deletions src/rules/GenericValidator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,22 @@ import {Data} from '../Data';
import {RuleConfig} from '../config/RuleConfig';
import * as util from 'util';

type ValidatorFunction = (
value: string,
config: RuleConfig,
data: Data
) => boolean;

/**
* A generic validator used to validate simple rules, specified passing a validatorFunction to the constructor.
*/
export class GenericValidator implements Rule {
private readonly config: RuleConfig;
private readonly validatorFunction: (path: string) => boolean;
private readonly validatorFunction: (
path: string,
config: RuleConfig,
data: Data
) => boolean;
private readonly defaultErrorMessage: string;
private readonly evaluateEmptyString: boolean;

Expand All @@ -21,7 +31,7 @@ export class GenericValidator implements Rule {
*/
constructor(
config: RuleConfig,
validatorFunction: (value: string) => boolean,
validatorFunction: ValidatorFunction,
defaultErrorMessage: string,
evaluateEmptyString = false
) {
Expand All @@ -33,7 +43,10 @@ export class GenericValidator implements Rule {
evaluate(path: string, data: Data): EvaluationResult {
const value = get(data, (this.config.path as string) || path) as string;

if ((value || this.evaluateEmptyString) && !this.validatorFunction(value)) {
if (
(value || this.evaluateEmptyString) &&
!this.validatorFunction(value, this.config, data)
) {
return {
valid: false,
field: path,
Expand Down

0 comments on commit abd9813

Please sign in to comment.