Custom error message for a Currency RegExp #723
-
I'm replacing Zod with Typebox due to the performance issues with Zod. We have a currency regex that we use to validate the form on the frontend and the payload to the server: amount: z
.string()
.regex(/^[+-]?[0-9]{1,3}(?:,?[0-9]{3})*(?:\.[0-9]{2})?$/, {
message: "Amount is an invalid currency",
})
.refine(
(val) =>
Transaction.dollarsToCents(val) <= 999900 && Transaction.dollarsToCents(val) >= -999900,
{
message: "Amount must be between -9999 and 9999",
}
), The issue is that we want to supply a custom error message for this currency. In Typebox, I've done the following: import { RegExp } from "@sinclair/typebox"
export const CURRENCY_SCHEMA = RegExp(/^[+-]?[0-9]{1,3}(?:,?[0-9]{3})*(?:\.[0-9]{2})?$/, {})
export function setupTypeBox() {
TypeRegistry.Set("Currency", (_schema, value) => Value.Check(CURRENCY_SCHEMA, value))
SetErrorFunction(({ schema, errorType, path, value }) => {
if (TypeGuard.IsKindOf(value, "Currency")) {
return "Please specify a valid currency."
}
return DefaultErrorFunction({ schema, errorType, path, value })
})
} I'm unsure this is going to work though. Heads up that one of the things that Zod excels at is the customization of error messages. I'm currently struggling with Typebox to recreate the same kind of DX. Because all of the validators are already functions, I would suggest adding an @sinclairzx81 thoughts? Thanks. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
@divmgl Hi, You can try the following which intercepts errors and allows you to return an import { SetErrorFunction, DefaultErrorFunction } from '@sinclair/typebox/errors'
import { Type, Static } from '@sinclair/typebox'
import { Value } from '@sinclair/typebox/value'
// Intercepts all errors and return an "errorMessage" string if defined, otherwise default.
SetErrorFunction(param => {
return typeof param.schema.errorMessage === 'string'
? param.schema.errorMessage
: DefaultErrorFunction(param)
})
// Creates a Currency Type, sets the errorMessage
export type Currency = Static<typeof Currency>
export const Currency = Type.RegExp(/^[+-]?[0-9]{1,3}(?:,?[0-9]{3})*(?:\.[0-9]{2})?$/, {
errorMessage: 'Currency string not valid'
})
const errors = Value.Errors(Currency, 'not-a-currency').First()
console.log(errors) // prints: {
// type: 48,
// schema: {
// errorMessage: 'Currency string not valid',
// type: 'RegExp',
// source: '^[+-]?[0-9]{1,3}(?:,?[0-9]{3})*(?:\\.[0-9]{2})?$',
// flags: '',
// [Symbol(TypeBox.Kind)]: 'RegExp'
// },
// path: '',
// value: 'not-a-currency',
// message: 'Currency string not valid' // <--- here
// } The Let me know if this helps. |
Beta Was this translation helpful? Give feedback.
@divmgl Hi,
You can try the following which intercepts errors and allows you to return an
errorMessage
passed via schema options.