Small validation library using type guards along with conditional and mapped types
npm install @davidk01/tiny-validatortest/test.ts for a use case. It is inlined below with an explanation of what is going on.
Strict if the validation is successful and Strict is a mapped type which converts all nullable fields
src/index.ts if you want to take a look. Anyway, carrying on with the example
typescript
import * as validation from '../src/index';
type Payload = {
f1?: string,
f2?: string[],
f3?: {
f1?: number,
f2?: string[]
}[]
};
`
Next we must define the validation type
`typescript
type PayloadValidation = validation.CombinedValidated
`
With the validation type defined we can create the description of the validation
`typescript
const payloadValidation: PayloadValidation = {
f1: { type: 'string', valid: _ => true },
f2: [{ type: 'string', valid: _ => true }],
f3: [{
f1: { type: 'number', valid: _ => true },
f2: [{ type: 'string', valid: _ => true }]
}]
};
`
Notice how each key in the payload is mapped to an object that specifies the type and a validation function that will
take the input at the specified key and then return true or false to indicate whether the field is valid.
In a production environment valid wouldn't vacuously return true but would actually be a function that incorporates
some domain knowledge.
Now let's define two payloads. One will be valid and the other will be invalid
`typescript
const validPayload: Payload = {
f1: '',
f2: [''],
f3: [
{
f1: 0,
f2: ['']
}
]
};
`
`typescript
const invalidPayload: Payload = {
f1: '',
f2: [''],
f3: [
{
f1: 0,
f2: ['', '']
}
]
};
`
The reason the second payload is invalid is a little subtle. In our validation prototype we defined f3[0].f2 to be
an array with a single element but in the payload we are supplying two elements. Since the length doesn't match
the payload is considered invalid.
Let's actually run and verify that the valid and invalid payloads are marked as such
`typescript
// Valid payload
if (validation.validator(validPayload, payloadValidation)) {
console.log('Received valid payload', JSON.stringify(validPayload));
} else {
console.log('Invalid payload', JSON.stringify(validPayload));
}
// Invalid payload b/c invalidPayload.f3.f2 has an extra key
if (validation.validator(invalidPayload, payloadValidation)) {
console.log('Received valid payload', JSON.stringify(invalidPayload));
} else {
console.log('Received invalid payload', JSON.stringify(invalidPayload));
}
`
First check will print the true arm of the if statement and the second will print the false arm because of
the length mismatch in one of the arrays.
`
$ tsc test/test.ts && node test/test/js
Received valid payload {"f1":"","f2":[""],"f3":[{"f1":0,"f2":[""]}]}
Received invalid payload {"f1":"","f2":[""],"f3":[{"f1":0,"f2":["",""]}]}
``