Security News
tea.xyz Spam Plagues npm and RubyGems Package Registries
Tea.xyz, a crypto project aimed at rewarding open source contributions, is once again facing backlash due to an influx of spam packages flooding public package registries.
validation.ts
Advanced tools
Readme
Validation for TypeScript
Every validator has a validate
function which returns a Result
A validated value can be transformed at any point during the validation process (e.g. isoDate
).
Errors are accumulated.
import { errorDebugString } from 'validation.ts'
const myValidator = ...
const result = myValidator.validate(myJson)
result.fold(
errors => console.error(errorDebugString(errors)),
validatedJson => console.log(validatedJson)
)
In case of errors, The Result
contains an Array of { message: string, context: string }
where message
is a debug error message for developers and context
is the path where the error occured (e.g root / data / 0 / name
)
errorDebugString
will give you a complete debug string of all errors, e.g.
At [root / c] Error validating the key. "c" is not a key of {
"a": true,
"b": true
}
At [root / c] Error validating the value. Type error: expected number but got string
import * as v from 'validation.ts'
v.string
v.number
v.boolean
v.null
v.undefined
v.isoDate
Sometimes, a string
or a number
is not just any string or number but carries extra meaning, e.g: email
, uuid
, userId
, KiloGram
, etc.
Tagging such a primitive as it's being validated can help make the downstream code more robust.
type UserId = string & { __tag: 'UserId' } // Note: You can use any naming convention for the tag.
const userIdValidator = v.string.tagged<UserId>()
import { literal } from 'validation.ts'
// The only value that can ever pass this validation is the 'X' string literal
const validator = literal('X')
import { array, string } from 'validation.ts'
const validator = array(string)
import { tuple, string, number } from 'validation.ts'
const validator = tuple(string, number) // Tuple2
import { string, object, union, optional } from 'validation.ts'
const person = object({
id: string,
prefs: object({
csvSeparator: optional(union(',', ';', '|'))
})
})
Note: For bigger unions of strings, consider using the keyof
validator instead.
Whereas optional
returns an T | undefined
, option
return an Option<T>
A dictionary is an object where all keys and all values share a common type.
import { dictionary, string, number } from 'validation.ts'
const validator = dictionary(string, number)
import Set from 'space-lift/object/set'
import { keyof } from 'validation.ts'
const keys = Set('aa', 'bb', 'cc').value()
const keyValidator = keyof(keys)
keyValidator.validate('bb') // Ok<'aa' | 'bb' | 'cc'> = Ok('bb')
// keyof typeof keys === typeof keyValidator.T === 'aa' | 'bb' | 'cc'
import { map, filter, string } from 'validation.ts'
const validator = string.filter(str => str.length > 3).map(str => `${str}...`)
import { recursion, string, array, object }
type Category = { name: string, categories: Category[] }
const category = recursion<Category>(self => object({
name: string,
categories: array(self)
}))
Note: this can be used with any combination of validators except ones using recursion
.
import { object, string, number } from 'validation.ts'
const person = object({
name: string,
age: number
})
type Person = typeof person.T
/*
type Person = {
name: string
age: number
}
*/
A Configuration object can be passed to modify the default behavior of the validators:
Configuration.transformObjectKeys
Transforms every keys of every objects before validating.
const burger = v.object({
options: v.object({
doubleBacon: v.boolean
})
})
const ok = burger.validate({
options: {
'double_bacon': true
}
}, { transformObjectKeys: v.snakeCaseTransformation })
To gcanti
and his io-ts
library which provided great inspiration.
FAQs
Validation for TypeScript
The npm package validation.ts receives a total of 226 weekly downloads. As such, validation.ts popularity was classified as not popular.
We found that validation.ts demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Tea.xyz, a crypto project aimed at rewarding open source contributions, is once again facing backlash due to an influx of spam packages flooding public package registries.
Security News
As cyber threats become more autonomous, AI-powered defenses are crucial for businesses to stay ahead of attackers who can exploit software vulnerabilities at scale.
Security News
UnitedHealth Group disclosed that the ransomware attack on Change Healthcare compromised protected health information for millions in the U.S., with estimated costs to the company expected to reach $1 billion.