Built a TypeScript form validator from scratch to actually learn TypeScript!

typescript dev.to

I kept copy-pasting TypeScript without really understanding it. I am leading a project where a major chunk is written by developers using ts and I felt lost. So I forced myself to build something without reaching for a library.

The result is a tiny type-safe form validator. You give it a schema and some data, it tells you what's wrong:

const result = validate<SignupForm>(
  {
    email:    { required: true, pattern: /\S+@\S+\.\S+/ },
    password: { required: true, minLength: 8 },
  },
  {
    email:    "notanemail",
    password: "abc",
  }
)
// { valid: false, errors: { email: ["Must be a valid email"], password: ["Minimum length is 8"] } }
Enter fullscreen mode Exit fullscreen mode

Honestly the TypeScript stuff was less confusing than I expected once I stopped trying to understand it abstractly and just wrote it.

Published it to npm as form-validator-ts.

If you're learning TypeScript, just build something small without a library. Two hours of confusion teaches more than two weeks of tutorials.

Try it

npm install form-validator-ts

GitHub: link | npm: link

Source: dev.to

arrow_back Back to Tutorials