DEV Community

TK
TK

Posted on

Validator in js

Hello world!!
I'm searching about validator in js and ts. So, I'm gonna write about my summary and conclution.!!

Comparing

Trends

Package Feature Merit Demerit Link
Zod TypeScript-first schema validation with static type inference Method chaining and easy to get ts type Newer package zod.dev
joi This is almost same to zod Have many plugins Doesn't support static type inference https://github.com/sideway/joi
Yup This is almost same to zod Have many plugins Missing some feature, function, deep object, promise... ... https://github.com/jquense/yup
class-validator Validate class properties Have many features Code isn't clean https://github.com/typestack/class-validator
ajv Validate by json scheme Enable to share schem to other languages Not supported typescript https://ajv.js.org/

Recommandation

If you don't validate by class

I recommand you zod.

If you want to use decorator for validation

I don't recommand you class-validator, instead of it, I recommand you some plugins.

For example, joiful. This is joi plugin.

zod

// In typescript
import { z } from 'zod'

const userScheme = z.object({
    username: z.string(),
    email: z.string().email()
})
type User = z.infer<typeof userScheme>

const data: User = {
    username: 'Takashi',
    email: 'not email'
}

// This code will throw validation error!!
const validated = userScheme.parse(data)

Enter fullscreen mode Exit fullscreen mode

Top comments (0)