Typescript Object Validator
A simple library for typescript projects to validating object shapes. You can use this package to declare the shape you'd like an object to align to. This is handy when you have a complex object (for example, an API response) and want to validate the object, AND have typescript recognize the shape.
Basic Usage
if elephantValidation.valid === true
API
validateObjectShape
Can be used to validate an object:
validateObjectShape objectDescription, validationItem, expectedObjectShape, validationOptions
- objectDescription (required - string): A description which is used in error messages when the object does not validate
- validationItem (required - object): An object you want to validate
- expectedObjectShape (required - object): A definition of what shape the object should match
- validationOptions (required - object): A set of options to change the validation behaviour, see more
The result of the validation is an object with a valid
property which flags if the validation succeeded or failed, a result
object which is the validated and typed object, or an errors
array with error results.
// If the validation is successful // If the validation fails
validateObjectShape
will coerce values for you if it's able to. For example if you say the property age
is a number, but it's passed in as a string, validateObjectShape
will try convert it to a number for you in the result
object:
if validationResult.valid === true
The library also alows you to test nested objects and arrays, for example:
Validation Types
There are a number of basic validation types available to use, and some helpers which allow you build more complex types:
Basic types
- string: Matches a string
- number: Matches a number
- boolean: Matches a boolean
- unknown: Matches an unknown type (will skip validation on that property)
This package also understands more complex types such as arrays and optional types. You can import helper functions to assist you in building these.
Complex Types:
- arrayOf ('string'): Array of some basic type
- optional ('string'): Makes the property your testing optional. The test will only run if the property exists
Options
- coerceValidObjectIntoArray (boolean): If you are validating an array with
arrayOf
, setting this totrue
will convert those properties to arrays for you, rather than returning an error. This is useful for example when converting from xml to json.
/* Converts names into an array. validationResult.result: { names: [{ fname: 'Jeff', lname: 'Thompson' }] }*/