DEV Community

Cover image for Valibot: A New Approach to Data Validation in JavaScript
Nick Taylor for OpenSauced

Posted on • Updated on • Originally published at opensauced.pizza

Valibot: A New Approach to Data Validation in JavaScript

I recently got to hang with the creator of Valibot, Fabian Hiller on a live stream. We discussed its history of the project and did some live coding with Valibot. Let’s dig in.

The history of Valibot

If video is your jam, check out this highlight from the live stream that summarizes the history of Valibot.

During his thesis work, developer Fabian Hiller found himself with dedicated time to pursue an idea he'd been mulling over - creating a new modular data validation library for JavaScript. This led to the birth of Valibot.

Fabian had previously worked on Modular Forms, but he wanted to bring that same modular philosophy to data validation. While popular validation libraries like Zod offer excellent APIs, Fabian felt there was room to take modularity even further.

"For Zod, it doesn't make sense to make it extremely modular as Valibot, because most Zod users love Zod for its API", Fabian explained. "This would probably be too big of a breaking change."

Instead of trying to rebuild Zod from the ground up, he decided a fresh start made more sense. Valibot aims for ultimate modularity, allowing developers to compose small, reusable validation units together.

Fabian didn't work in isolation. He reached out to Zod's creator Colin McDonnell, but the timing didn't line up for deeper collaboration initially. Fabian remains in touch with McDonnell and other open source maintainers though.

"I'm sure improvements I made in Valibot will hopefully improve other libraries, and other libraries will hopefully affect and improve Valibot," he said. "I hope at the end we end up with great open source projects, and the community can choose what they prefer."

With Valibot, Fabian hopes to provide developers a new, composable approach to data validation. And by cross-pollinating with other libraries, he aims to push the entire JavaScript validation ecosystem forward.

A First Look at Valibot

If you want to experiment with Valibot, I recommend you check out the Valibot playground. Fabian actually made a change to enable prettier support after our live stream! 🤩

Also, version 0.31.0 was recently released with a whole rework of the API.

Let's start of simple. We want to create an e-mail validator. Valibot makes this pretty easy for us.

import * as v from 'valibot';

const EmailSchema = v.pipe(v.string(), v.email());

const validEmail = v.safeParse(EmailSchema, 'jane@example.com');

console.log(validEmail);
Enter fullscreen mode Exit fullscreen mode

First, we import the Valibot package. Next, we create a schema for a valid email, const EmailSchema = v.pipe(v.string(), v.email());

v.pipe is so powerful. It allows us to chain validators. First, we check that the input is a string via v.string(), and next, if it's a valid email via v.email().

If you run this in the playground, you'll get the following output.

[LOG]: {
  typed: true,
  success: true,
  output: "jane@example.com",
  issues: undefined
}
Enter fullscreen mode Exit fullscreen mode

You can view the following example in this Valibot playground.

Let's see what happens when we have an invalid email.

import * as v from 'valibot';

const EmailSchema = v.pipe(v.string(), v.email());

const validEmail = v.safeParse(EmailSchema, 'janeexample.com');

console.log(validEmail);
Enter fullscreen mode Exit fullscreen mode

If we run the updated playground, it will now output the following:

[LOG]: {
  typed: true,
  success: false,
  output: "janeexample.com",
  issues: [
    {
      kind: "validation",
      type: "email",
      input: "janeexample.com",
      expected: null,
      received: "\"janeexample.com\"",
      message: "Invalid email: Received \"janeexample.com\"",
      requirement: RegExp,
      path: undefined,
      issues: undefined,
      lang: undefined,
      abortEarly: undefined,
      abortPipeEarly: undefined
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

You can view the updated example in this Valibot playground.

You can see an example of valibot in action in a recent pull request of mine.

  if (context.query.id) {
    try {
      sharedChatId = parseSchema(UuidSchema, context.query.id);
      searchParams.set("id", sharedChatId);
    } catch (error) {
      captureException(new Error(`Failed to parse UUID for StarSearch. UUID: ${sharedChatId}`, { cause: error }));
      throw new Error("Invalid shared Chat ID");
    }
  }
Enter fullscreen mode Exit fullscreen mode

feat: enabled loading an existing conversation in StarSearch #3563

Description

Now you can share an existing thread (conversation in StarSearch). We had a rudimentary version of this previously (see #3324), but it was just sharing the prompt and running it.

These shared conversations are the full conversation that gets replayed and does not hit our AI backend at all.

If you are not logged in, you will only be able to replay it once (unless the page is refreshed in the browser) and any other actions will require you to log in.

One thing to note is if you generate a shared URL, it will generate for beta.app.opensauced.pizza on beta and deploy previews, and one in prod, will be prod links. All that said, you'll just need to replace the beta base URL with the deployment preview URL.

TODO:

  • fix flash of content when loading a conversation - fix OG image for a shareable StarSearch conversation - fix Server-side request forgery warnings

Note: This PR adds Valibot to the project. It is MIT licensed and a small package (1kb). It's used for some validation in this PR and I plan to use it elsewhere in the application long term.

Related Tickets & Documents

Closes #3551

Mobile & Desktop Screenshots/Recordings

Steps to QA

Here's a few share links you can try:

Associated OG image, https://deploy-preview-3563--oss-insights.netlify.app/og-images/star-search/?id=900686cc-8926-47fd-a1d6-0e19da967f48

Associated OG image, https://deploy-preview-3563--oss-insights.netlify.app/og-images/star-search/?id=ff9b26b7-64e7-460b-9d33-252543bee24d

--

Also try and create a new conversation then try to share it.

Tier (staff will fill in)

  • [ ] Tier 1
  • [ ] Tier 2
  • [x] Tier 3
  • [ ] Tier 4

[optional] What gif best describes this PR or how it makes you feel?

Contributing to Valibot

Valibot is open source, like many things in the JavaScript ecosystem.

The project has a low lottery factor, and it also has high contributor confidence (many stargazers and forkers come back later on to make a meaningful contribution).

Valibot repository page on OpenSauced

If you're looking to contribute to open source in the JavaScript/TypeScript ecosystem, Valibot might be up your alley.

Wrapping Up

We only scratched the surface of Valibot, but I encourage you to check it out. Valibot was highlighted in the latest bytes.dev issue, VALIBOT AND THE CIRCLE OF LIFE. You know a library is gaining traction if bytes.dev covers it!

Stay saucy peeps!

If you would like to know more about my work in open source, follow me on OpenSauced.

Top comments (12)

Collapse
 
bekahhw profile image
BekahHW • Edited

It's interesting to see a lot of project's lottery factor correlate with their contrib confidence. You can also find more about the lottery factor here:

Collapse
 
nickytonline profile image
Nick Taylor

100%

Collapse
 
nickytonline profile image
Nick Taylor

Fabian (creator of Valibot) mentioned the following which I'll update in the blog post:

  • "If this were running in an application, it would throw". It only throws when using v.parse, v.safeParse does not throw.
Collapse
 
hinogi profile image
Stefan Schneider

Just to add another one to the stack of validation libs
effect/schema

Collapse
 
nickytonline profile image
Nick Taylor

Yeah the Effect ecosystem is super interesting. I actually had a chance to chat with the creator of Effect recently if you want to check it out.

An Introduction to Effect - YouTube

Effect is a powerful TypeScript library designed to help developers easily create complex, synchronous, and asynchronous programs. Michael Arnaldi, Creator o...

favicon youtube.com
Collapse
 
hinogi profile image
Stefan Schneider

I am still wrestling with it. NestJS which I use for backend stuff, already has a lot of those build in or has comparable concepts at least, via DI.
In Frontend, I am absolutely lost on where to put it.
I especially like the tagged Errors and such.

Collapse
 
nickytonline profile image
Nick Taylor • Edited

If you're interested in catching the recording of our live stream, you can check it out below.

While you're there, smash that subscribe button. It's appreciated. 😎

Collapse
 
matin_mollapur profile image
Matin Mollapur

That's cool!

Collapse
 
nickytonline profile image
Nick Taylor

Yeah!

A T-Rex saying Yeah!

Collapse
 
kansoldev profile image
Yahaya Oyinkansola

I really like the idea behind this library, it cam be built up from something useful to something complex, would see how I can use it in my next Project

Collapse
 
nickytonline profile image
Nick Taylor

Yeah I really like the project and the pipe function is soooo goood.

Hackerman from Kung Fury putting on a Nintendo Power glove

Collapse
 
collectivecloudperu profile image
Nube Colectiva

Thanks for the tool, it has a very good UI.