Browse Source

Add `is` predicate to provide custom validation functions (#55)

iss58
Sam Verschueren 7 years ago
committed by Sindre Sorhus
parent
commit
c87999fbca
  1. 14
      source/lib/predicates/predicate.ts
  2. 10
      source/test/test.ts

14
source/lib/predicates/predicate.ts

@ -51,6 +51,20 @@ export class Predicate<T = any> {
return not(this);
}
/**
* Test if the value matches a custom validation function. The validation function should return `true` if the value
* passes the function. If the function either returns `false` or a string, the function fails and the string will be
* used as error message.
*
* @param fn Validation function.
*/
is(fn: (value: T) => boolean | string) {
return this.addValidator({
message: (value, error) => error || `Expected \`${value}\` to pass custom validation function`,
validator: value => fn(value)
});
}
/**
* Register a new validator.
*

10
source/test/test.ts

@ -8,6 +8,16 @@ test('not', t => {
t.throws(() => m('' as any, m.string.not.empty), '[NOT] Expected string to be empty, got ``');
});
test('is', t => {
const greaterThan = (max: number, x: number) => {
return x > max || `Expected \`${x}\` to be greater than \`${max}\``;
};
t.notThrows(() => m(1, m.number.is(x => x < 10)));
t.throws(() => m(1, m.number.is(x => x > 10)), 'Expected `1` to pass custom validation function');
t.throws(() => m(5, m.number.is(x => greaterThan(10, x))), 'Expected `5` to be greater than `10`');
});
test('reusable validator', t => {
const checkUsername = m.create(m.string.minLength(3));

Loading…
Cancel
Save