Skip to content

Commit

Permalink
feat: add min/max rules to NumberValidator
Browse files Browse the repository at this point in the history
  • Loading branch information
emyann committed Jul 26, 2019
1 parent bcf66c1 commit 7c72a40
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 0 deletions.
54 changes: 54 additions & 0 deletions src/validation/reporter.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,60 @@ describe('Reporter', () => {
expect(errors).toBeNull();
expect(result).toEqual({ t1: 1234 });
});

it('should report an error when number is greater than max rule', () => {
interface S {
s1: number;
}
interface T {
t1: number;
}

const VALUE = 10;
const MAX = 5;
const schema = createSchema<T, S>({
t1: {
fn: value => value.s1,
validation: Validation.number().max(MAX)
}
});
const result = morphism(schema, { s1: VALUE });
const error = new ValidationError({ targetProperty: 't1', expect: `value to be less or equal than ${MAX}`, value: VALUE });
const message = defaultFormatter(error);
const errors = reporter.report(result);
expect(errors).not.toBeNull();
if (errors) {
expect(errors.length).toEqual(1);
expect(errors[0]).toBe(message);
}
});

it('should report an error when number is less than min rule', () => {
interface S {
s1: number;
}
interface T {
t1: number;
}

const VALUE = 2;
const MIN = 5;
const schema = createSchema<T, S>({
t1: {
fn: value => value.s1,
validation: Validation.number().min(MIN)
}
});
const result = morphism(schema, { s1: VALUE });
const error = new ValidationError({ targetProperty: 't1', expect: `value to be greater or equal than ${MIN}`, value: VALUE });
const message = defaultFormatter(error);
const errors = reporter.report(result);
expect(errors).not.toBeNull();
if (errors) {
expect(errors.length).toEqual(1);
expect(errors[0]).toBe(message);
}
});
});

describe('boolean', () => {
Expand Down
27 changes: 27 additions & 0 deletions src/validation/validators/NumberValidator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,31 @@ export class NumberValidator extends BaseValidator<number> {
}
});
}

min(val: number) {
this.addRule({
name: 'min',
expect: `value to be greater or equal than ${val}`,
test: function(value) {
if (value < val) {
throw new ValidatorError({ value, expect: this.expect });
}
return value;
}
});
return this;
}
max(val: number) {
this.addRule({
name: 'max',
expect: `value to be less or equal than ${val}`,
test: function(value) {
if (value > val) {
throw new ValidatorError({ value, expect: this.expect });
}
return value;
}
});
return this;
}
}

0 comments on commit 7c72a40

Please sign in to comment.