🌐
Medium
medium.com › @djoepramono › how-to-validate-javascript-object-better-with-typescript-e43314d97f9c
How to Validate JavaScript Object Better with TypeScript | by Djoe Pramono | Medium
October 16, 2019 - Here we use InvalidOr<T> as the return type which is a union type of either Invalid or T. T here is a generic, it’s the type of the object that we are validating. It can be a string, array, or even an object. In our case, this is Person. So our function can be written as follows ... Unfortunately the latter might cause a linting error in you are using typescript-eslint default setting
🌐
npm
npmjs.com › package › validate-typescript
validate-typescript - npm
August 9, 2019 - Extensible schema based validator that supports typescript typing.. Latest version: 4.0.2, last published: 7 years ago. Start using validate-typescript in your project by running `npm i validate-typescript`. There are 7 other projects in the ...
      » npm install validate-typescript
    
Published   Aug 09, 2019
Version   4.0.2
Author   Grant Zietsman
🌐
Validatejs
validatejs.org
validate.js
Fixed a bug that caused the validations to fail if the value was a promise. Thanks bbusschots-mu for reporting this. Fixed a bug that caused form input names not to be properly escaped. Thanks James Tudsbury for reporting this. Fix a bug in IE11. Thanks Shawn Doucet for fixing this. The typescript ...
🌐
npm
npmjs.com › package › @types › validator
@types/validator - npm
November 17, 2025 - TypeScript definitions for validator. Latest version: 13.15.10, last published: 4 months ago. Start using @types/validator in your project by running `npm i @types/validator`. There are 672 other projects in the npm registry using @types/validator.
      » npm install @types/validator
    
🌐
GitHub
github.com › ansman › validate.js › issues › 209
TypeScript definitions · Issue #209 · ansman/validate.js
May 8, 2017 - null : "must be a string"; }; validate.formatters.custom = function(errors) { return errors.map(function(error) { return error.validator; }); }; const constraints = { username: { presence: true, exclusion: { within: ["nicklas"], message: "'%{value}' is not allowed" } }, password: { presence: true, length: { minimum: 6, message: "must be at least 6 characters" } } }; const errors = validate({ password: "bad" }, constraints, { format: "custom" }); console.log(errors); ❯ yarn test yarn test v0.23.4 $ tsc --allowJs --checkJs --noEmit *.js test.js(4,10): error TS2339: Property 'validators' does n
🌐
GitHub
github.com › shellyln › tynder
GitHub - shellyln/tynder: TypeScript friendly Data validator for JavaScript.
TypeScript friendly Data validator for JavaScript. Validate data in browsers, node.js back-end servers, and various language platforms by simply writing the schema once in TypeScript with extended syntax.
Author   shellyln
🌐
GitHub
github.com › typestack › class-validator
GitHub - typestack/class-validator: Decorator-based property validation for classes. · GitHub
Allows use of decorator and non-decorator based validation. Internally uses validator.js to perform validation.
Starred by 11.7K users
Forked by 843 users
Languages   TypeScript 99.8% | JavaScript 0.2%
Top answer
1 of 6
5

UPDATE 2022:

I stumbled upon Runtypes and I think it is quite a cool solution. And when you think of it, quite an obvious one: You use a solution in the middle that automatically gives you correct types and a possibility to check the validity. It's much better than trying to work from types to validating, since interfaces don't exist in runtime as was said multiple times.

ORIGINAL ANSWER:

Yeah, I understand that interfaces don't exist in runtime. I created this solution, that validates my input and gives me type errors, when I need them. I think my title was bit misleading, so I'll also change the title to "What is the best way to automatically validate requests using Typescript".

The idea is to force me to write a simple schema for each interface I wish to use to validate a backend endpoint. Also, in order to minimize the possibility to human errors, it is important that my linter type checks the validatorObject.

validateParams.ts:

Copyconst validateParams: (targetObject: any, validatorObject: any) => boolean = (targetObject, validatorObject) => {
    if (typeof targetObject !== typeof validatorObject) return false
    if (typeof targetObject === 'object') {
        let validObject = true
        if (Array.isArray(targetObject)) {
            for (let subObject of targetObject) {
                validObject = validObject && validateParams(subObject, validatorObject[0])
            }
        } else {
            for (let key of Object.keys(validatorObject)) {
                if (typeof targetObject[key] === 'object') validObject = validObject && validateParams(targetObject[key], validatorObject[key])
                if (typeof targetObject[key] !== typeof validatorObject[key]) validObject = false
            }
        }
        return validObject
    }
    return true
}

export default validateParams

authenticate.ts

Copyimport { Request, Response } from 'express'
import validateParams from "./validateParams"

interface AuthenticateParams {
    email: string
    password: string
}

const validatorObject: AuthenticateParams = {
    email: 'string',
    password: 'string'
}

type AuthenticationRequest = Request & {body: AuthenticateParams}

const authenticate = async (req: AuthenticationRequest, res: Response) => {
    if (!validateParams(req.body, validatorObject)) res.status(400).send('Invalid body')

    // DO STUFF
    let stuff

    res.status(200).send(stuff)
}

export default authenticate

updateUser.ts

Copyimport { Request, Response } from 'express'
import validateParams from "./validateParams"

interface UpdateUserParams {
    name: string
    products: {
        name: string
        price: number
    }[]
}

const validatorObject: UpdateUserParams = {
    name: 'string',
    products: [{name: 'string', number: 0}]
}

type AuthenticationRequest = Request & {body: UpdateUserParams}

const updateUser = async (req: UpdateUserParams, res: Response) => {
    if (!validateParams(req.body, validatorObject)) res.status(400).send('Invalid body')

    // DO STUFF
    let stuff

    res.status(200).send(stuff)
}

export default updateUser

This is not the most beautiful solution, but I like that it validates my requests automatically and also gives me errors, if I forget to update my validatorObject. But yeah, it would be awesome to get the Typescript interfaces in runtime.

2 of 6
3

If you also maintaining openapi documentation, you can validate the request using express-openapi-validator. It is also available for fastify and Koa

🌐
LogRocket
blog.logrocket.com › home › dynamic type validation in typescript
Dynamic type validation in TypeScript - LogRocket Blog
June 4, 2024 - As these annotations are wrapped inside comments, they don’t present any conflict with the TypeScript compiler. This method is based on the idea that the developer will run the CLI command and generate the validators; otherwise, there’s a possibility that the schema was generated with an older version of the type, which can then present mismatches. Fixing this issue is quite easy: you simply have to add a script that will be executed before your code will run. You can call it prebuild or prestart, and this is how your package.json might look:
Find elsewhere
🌐
npm
npmjs.com › package › typescript-validator
typescript-validator - npm
January 29, 2018 - Latest version: 1.0.2, last published: 8 years ago. Start using typescript-validator in your project by running `npm i typescript-validator`. There are 3 other projects in the npm registry using typescript-validator.
      » npm install typescript-validator
    
Published   Jan 29, 2018
Version   1.0.2
🌐
DEV Community
dev.to › koistya › using-validate-js-via-a-fluent-typescript-interface-3hcm
Using Validate.js via a fluent TypeScript interface - DEV Community
March 23, 2021 - This interface needs to be strongly typed, allowing a better development experience (DX) when used with TypeScript. I think validator.js (✭17k) fits perfectly into the first requirement.
🌐
Medium
medium.com › @victorgrecotech › how-to-do-data-validation-with-typescript-without-increasing-your-technical-debt-db23beb40112
How to do data validation with TypeScript — without increasing your technical debt | by Victor Greco | Medium
August 13, 2024 - Now not only can you keep your validation logic and your types in the same file, but you can also keep them in sync by deriving your validation schema from your TypeScript types! Isn’t that amazing?
🌐
Nozzlegear
nozzlegear.com › blog › build-a-simple-object-validation-utility-with-typescript
Build a simple object validation utility with TypeScript | Nozzlegear Software
With that small ruleset in place, we can set up a switch statement in the .checkRule function and return either an okay result if an individual rule passes, or an error result if it doesn't. Since we used a union type of several different interfaces for the StringRule, the TypeScript compiler will know when the rule has a .max, .min or .value property, complete with intellisense. Depending on your tsconfig.json settings, it will also complain if you forget to check each different case in a switch statement.
🌐
npm
npmjs.com › package › validator.ts
validator.ts - npm
March 28, 2016 - Allows to use decorator and non-decorator based validation in your Typescript classes. Internally uses validator.js to make validation and sanitization.
      » npm install validator.ts
    
Published   Mar 28, 2016
Version   0.2.2
Author   Umed Khudoiberdiev
Top answer
1 of 6
3

This question is old, but I'd like to share my validation library also.

It's type-script friendly, tiny (no tons of unnecessary functionality) and easily extensible by custom validators.

npm: https://www.npmjs.com/package/checkeasy

github: https://github.com/smbwain/checkeasy

import {alternatives, arrayOf, int, object, oneOf, optional, string} from 'checkeasy';

const myValidator = object({
   a: int({max: 5}),
   b: string(),
   c: optional(float()),
   d: oneOf(['a', 'b', 7] as const),
   e: alternatives([string(), int()]),
   f: arrayOf(string()),
   g: object({
       subP: string(),
   }),
});

const value = myValidator(anyUnsafeData, 'name');
// type of value is: {
//    a: number,
//    b: string,
//    c: number | undefined,
//    d: "a" | "b" | 7,
//    e: string | number,
//    f: string[],
//    g: {subP: string},
//}

It also throws clear human readable messages in errors. E.g.

myValidator({a: 'hello'}, 'data');
// throws: [data.a] should be an integer

myValidator({a: 1, b: 'string', d: 'a', e: true}, 'data');
// throws: All alternatives failed for [data.e]:
//      [data.e.@alternative(0)] should be a string
//      [data.e.@alternative(1)] should be an integer
2 of 6
2

I've created a super lightweight library called Smoke Screen which does exactly that. It leverages typescript features to perform any kind of object validation within javascript runtime. It's not 100% seamless due to the fact that javascript does not hold any type information at runtime, but thanks to TypeScript decorators, this may be easily done:

class Person {

    @exposed({type: Number})
    age: number;

}

// serialize a Person object into a JSON string
const person = new Person();
person.age = 56.8;
const smokeScreen = new SmokeScreen();
smokeScreen.toJSON(person); // -> '{"age":56.8}'

// deserialize a JSON string into a Person object
let json = JSON.stringify({age: 19});
const person2 = smokeScreen.fromJSON(json, Person);
console.log(person2); // -> Person { age: 19 }

// typing validation
json = JSON.stringify({age: "oops"});
smokeScreen.fromJSON(json, Person); // Error: illegal input - property 'age' must be a number

Additional custom validators may be set, optional parameters and null checking are also supported and enforced. I suggest reading more about it and trying it out.

🌐
Ajv
ajv.js.org › guide › typescript.html
Using with TypeScript | Ajv JSON schema validator
Ajv takes advantage of TypeScript type system to provide additional functionality that is not possible in JavaScript: utility types JSONSchemaType and JTDSchemaType to convert data type into the schema type to simplify writing schemas, both for JSON Schema (but without union support) and for JSON Type Definition (with tagged unions support). utility type JTDDataType to convert JSON Type Definition schema into the type of data that it defines. compiled validation functions are type guards that narrow the type after successful validation.
🌐
xjavascript
xjavascript.com › blog › npm-validator-typescript
Mastering npm Validator with TypeScript — xjavascript.com
Navigate to your project directory in the terminal and run: ... The @types/validator package provides TypeScript type definitions for the validator library, enabling TypeScript to understand the types used in the validator ...
🌐
npm
npmjs.com › package › just-validate
just-validate - npm
November 13, 2023 - written in Typescript and good test coverage · npm install just-validate --save · yarn add just-validate · And then use it as an imported module: import JustValidate from 'just-validate'; const validate = new JustValidate('#form'); Or if you don't use module bundlers, just include JustValidate script on your page from CDN and call it as window.JustValidate: <script src="https://unpkg.com/just-validate@latest/dist/just-validate.production.min.js"></script> <body> <script> const validate = new window.JustValidate('#form'); </script> </body> There are plenty of rules which you could use out of the box: required, non-empty fields ·
      » npm install just-validate
    
Published   Nov 13, 2023
Version   4.3.0
Author   Georgii Perepecho