Verified (13.7k minified)
A class for validating data created by me for SafetyWing
Supported types
string
number
boolean
object
any
null
undefined
function
T[]
Array<T>
You can also use any literal value.
Usage
;const isString = "string";const isNumber = "number";const isList = "any[]";const isObject = "object"; isStringisValid -> trueisNumberisValid -> trueisListisValid -> trueisObjectisValid -> true
A more detailed example
; // Let's imagine we have some data coming from the user on our serverconst types = { return /^A$/; } { return /^[A-Z][a-z]+ [A-Z][a-z]+$/; } { return /^[0-9]${5}/; } { return /^[A-Z][0-9][A-Z] [0-9][A-Z][0-9]$/; } { return value !== "Invalid Date"; } "MedicalHistory": doctor: "string" reason: "string" date: "Date" hospital: "string" ; const validator = userID: "UserID" fullName: "FullName" zipCode: "ZipCode|PostalCode" medicalHistory: "MedicalHistory[]" types;
Object structure
Valid
;let v = name: "string"; v; -> value: name: true data: name: "Sean MacIsaac" type: name: "string" isValid: true invalid:
Invalid
When an object is invalidated, you will get a list of the invalid values and their paths.
;let v = name: "string"; v; -> value: name: false data: name: undefined type: name: "string" isValid: false invalid: pathname: "name" value: undefined expected: "string"
Custom types
You can create custom types to reduce repetive boilerplate
Global types
Validator;
Or you can define the type literally
Validator;
shoes: "Shoe[]" ; -> value: shoes: size: true brand: true size: true brand: true data: shoes: size: 12 brand: "Nike" size: 11 brand: "Asics" type: shoes: "Shoe[]" isValid: true invalid:
Local types
This is a validation type which exists only on a specific instance of Validator
const validator = shoes: "Shoe[]" { const types = size: "number" brand: "string" ; return types } // Or as an object literal Boot: size: "number" brand: "string" season: "string" ;
Union types
const validator = "[string]": "Array<Shoe|string>"; validator;
Optional parameters
parameter?
Typed object keys
[string]: { value: "string" }
Optional typed object keys
[string]?: { value: "string" }
Extending types
Sometimes we want to share properties from one type to the next, extending a type allows you to do just that.
Validator; const validator = "Shoe"; validator;