Library for validating objects in a declarative and functional way.
const isOptionallyNumber = optionally(isNumber);
const propNameValidator = property('propName', isOptionallyNumber);
const otherPropValidator = property('otherProp', isNumber);
// Merge two validators into one validator
const objectValidator = merge([
propNameValidator,
otherPropValidator
] as const); // It is important to use const for proper type infenrece
type ValidObjectType = Infer<typeof objectValidator>;
// type ObjectType = {
// propName: number | undefined;
// propName2: number;
// }
let result = objectValidator({ otherProp: 10 });
// result = []
let result = objectValidator({ propName: 10 });
// result = [{ field: 'otherProp', type: 'isNotANumber', message: 'Field should be a number' }]
let result = objectValidator({ otherProp: '10', propName: 10 });
// result = [{ field: 'otherProp', type: 'isNotANumber', message: 'Field should be a number' }]
let result = objectValidator({ otherProp: '10', propName: '10' });
// result = [
// { field: 'propName', type: 'isNotANumber', message: 'Field should be a number' },
// { field: 'otherProp', type: 'isNotANumber', message: 'Field should be a number' }
// ];Behaviour incompatibilities with validation-middleware
The fun-validations has been designed to be a drop-in replacement for the validation-middleware library so in most cases you can simply replace the imports from one lib to the other an it will produce the same results in terms of validation and messages.
There are however a few exceptions:
isIterable: This validator does pass with JS Objects anymore. It can only be used for truly iterable objects that implement the iterable protocal like arrays or strings.
Infer with property validator returns a type with non-optional properties as optional
This may happen if the tsconfig does not perform strictNullChecks. To fix this, change strictNullChecks to true or directly use strict mode.
Infer with compose/merge that uses property validator returns a type that only contains the type of the first property validator
Add as const at the end of the array of validators that are passed to compose/merge
const isNiceAsync = createValidator<'nice'>((value: unknown) => Promise.resolve(value === 'nice'), { type: 'isNotNice',message: 'Field should be nice' });
type isNiceType = Infer<typeof isNiceAsync>;
// type isNiceType = 'nice';
let result = await isNiceAsync('nice');
// result = []
let result = await isNiceAsync('not-nice');
// result = [{ type: 'isNotNice',message: 'Field should be nice' }]
let promiseOfResult = isNiceAsync('nice');
// promiseOfResult = Promise<ValidationErrorDescription>;
let result = await promiseOfResult;
// result = [];