I'm currently learning schema validation for the first time and I'm using typebox, but I can't define custom error messages for my types. With a prop like:
name: Type.String()
I could attach:
.min(2, { message: "Name must be 2 or more characters long" })
with the Zod lib, but I still haven't found something like that in typebox docs or discussions. I chose this library because of how lightweight it is, but for now I'll look into other libraries with react-hook-form. Thanks in advance!
You can change the default typebox error function to respect the message
property
https://github.com/sinclairzx81/typebox?tab=readme-ov-file#error-function
import {
DefaultErrorFunction,
SetErrorFunction,
} from '@sinclair/typebox/errors';
SetErrorFunction((e) => {
if (e.schema.message && typeof e.schema.message === 'string') {
return e.schema.message;
}
return DefaultErrorFunction(e);
});
Then
Type.String({message: 'example custom error message'})
will raise the error message you want,
Though from your example, you might want to set the message
to be an object / function to be able to process the error by cases using e.errorType
value.