valibot: Parser crash for nonOptional / nonNullish wrapped around transformers emit undefined

While building a base type which maps empty strings to undefined, I stumbled about the minLength & maxLength functions crashing, when passed an undefined value which was wrapped in a nonOptional or nonNullish:

import * as v from 'valibot';

const String = v.nonOptional(
  v.pipe(
    v.string(),
    v.transform((val) => val?.trim() || undefined),
  ),
);

const Password = v.pipe(String, v.minLength(6))

const Schema = v.object({
  password: Password
});

const result = v.safeParse(Schema, {
  password: "",
});

console.log(result);

This actually crashes the execution, even though safe Parse is used:

[error]: TypeError: Cannot read properties of undefined (reading 'length')
    at ~validate (https://valibot.dev/assets/Cb45s_t9-index.min.js:1:18263)
    at ~validate (https://valibot.dev/assets/Cb45s_t9-index.min.js:1:64883)
    at ~validate (https://valibot.dev/assets/Cb45s_t9-index.min.js:1:45222)
    at Module.Ae (https://valibot.dev/assets/Cb45s_t9-index.min.js:1:65578)
    at about:srcdoc:152:18

Playground example: https://valibot.dev/playground/?code=JYWwDg9gTgLgBAKjgQwM5wG5wGZQiOAcg2QBtgAjCGQgbgCh6BjCAO1XgGUYphWBzOAF5MAOlZsA8mBjA2ZABT04YsMDABTJSpUZRHXgIUBKADTKdensnbZoIBQpKljwgHyYyAflE9QJuAAfQLgAV1YAEw1sPg0IswsE4wZmNg44AAU0VAB3aAjhVXUtbkN+UzEQPgAZDQEYAAsFADZjY0YWdi4mBo0QZEK9CAoAKw0mGAUAbwswbLyoCIAuTPn8+gBfZI60+CgNVFDSeBE9VGRsDSyoVBKevuQKmZU51Fz8lYAiT-MtlM7UBBSBpRKQIPwFPtDsdtkA

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 16 (10 by maintainers)

Commits related to this issue

Most upvoted comments

Awesome, if you’re ever in the Ruhrgebiet in Germany let me invite you to a coffee / dinner / beer ❤️

Fixed! 😎 v1.0.0-beta.5 is available!

Thank you for your feedback! Checking the output is a good idea and might be the best solution with the least drawbacks. I will think about it.

We have the same problem with optional, nullable and nullish when a default value is provided, because in this case we also “remove” undefined and/or null from the output type. But checking the output and returning an issue if the value is undefined and/or null feels somehow wrong for these schemas. 🙃

Regarding DX in general Valibot is the best thing I’ve used yet. I love the composability, super easy to extend with your own schemas (which is what happens largely in big projects anyway). I actually prefer the syntax over zod 👍