fabian-hiller / valibot

The modular and type safe schema library for validating structural data 🤖
https://valibot.dev
MIT License
5.67k stars 170 forks source link

cannot pipe a pipe #609

Closed y-nk closed 1 month ago

y-nk commented 1 month ago

I'm trying to write custom validators and i thought i could do something like:

const myCustomValidator = (length: number) => pipe(
  string(),
  maxLength(length),
)

const MySchema = object({
  someString: pipe(
    notEmpty(),
    myCustomValidator(1),
  )
})

of course, this is a dumb example and i know i can probably get out with:

-const myCustomValidator = (length: number) => pipe(
+const myCustomValidator = (length: number) => ([
  string(),
  maxLength(length),
-)
+])

const MySchema = object({
  someString: pipe(
    notEmpty(),
-    myCustomValidator(1),
+    ...myCustomValidator(1),
  )
})

but i'd be loosing type safety of the pipe call in the myCustomValidator function... so i was curious if this could be done, and how?

fabian-hiller commented 1 month ago

This works but you can't use an action as the first argument of pipe. See this playground.

import * as v from 'valibot';

const myCustomValidator = (length: number) => v.pipe(
  v.string(),
  v.maxLength(length),
)

const MySchema = v.object({
  someString: v.pipe(
    v.string(), // <-- Schema required
    myCustomValidator(1),
  )
});
y-nk commented 1 month ago

ah, i see. thanks for this, it makes sense.