DEV Community 👩‍💻👨‍💻

T-Kisaku
T-Kisaku

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)

This post blew up on DEV in 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!