Value validation
threema-danilo opened this issue ยท 3 comments
Is it possible to do validations on the value, which is not part of the type information (e.g. only allowing numbers 0-255, or only strings matching a RegEx)? Or is that out of scope?
There seems to be code to validate the length of arrays, but I think right now this is only used for tuples, which are covered by TypeScript's type system.
Yes, that's what the .assert()
method is for. It allows you to add a custom validator function and pass a custom error message. In your case it would look like this:
import * as v from "@badrap/valita";
const schema = v
.number()
.assert((v) => v >= 0 && v <= 255, "Must be in between 0 or 255");
schema.parse(2); // works
schema.parse(-1); // Throws "Must be in between 0 or 255"
schema.parse(300); // Throws "Must be in between 0 or 255"
For regex you can do the same:
import * as v from "@badrap/valita";
const schema = v
.string()
.assert((v) => /my-cool-regex/.test(v), "Must match regex");
Although to be fair a buit-in regex matcher would be even nicer. Sounds like a feature that's easy enough to add via a PR ๐
Ah, nice, thanks for the quick reply! Might be something worth mentioning in the README ๐
Thank you!