Frontend custom validation messages

Decision

We continue using yup for frontend form validation for now, but keep an eye out for problems.

Problems

We decided to use typebox for all validation usecases, including frontend form validation - which we expected to work, as there's an existing useForm hook resolver. Now that we got to work we forms again, we realize that typebox may not actually be a best solution for this particular usecase, as it's not giving us a required freedom to generate custom error messages. To continue, we'll need to make a decision on an approach to form validation.

Context

Our usage pattern for yup custom error messages predominantly employs 2 or more different validators with different messages, e.g.

yup
  .string()
  .required("generic.error.required-field")
  .trim("generic.error.whitespaces")
  .min(3, "generic.error.min-3")

Typebox has completely different approach to customizing error messages, namely you use the SetErrorFunction which globally modifies the behavior of Type and Value:

SetErrorFunction((error) => {
  switch (error.errorType) {
    case ValueErrorType.ArrayContains:
      return "typebox.ArrayContains";
    case ValueErrorType.ArrayMaxContains:
      return "typebox.ArrayMaxContains";
      (...)

There's no straightforward way to modify the error message for a single schema, much less with multiple conditional messages.

Options

  • we try to reimplement the custom error message functionality in typebox
  • we continue using yup for form validation
  • we investigate other options
    • zod (the team has already used it in frontend context in admin-dashboard)
  • we try to achieve schema-neutrality with Standard Schema, though it doesn't seem to support typebox yet

Reasoning

Reimplementing more expressive custom error message interface for typebox schemas would require a sizeable amount of code to write and maintain, just for the sake of keeping the same schema format, and we decided against it.

Also, if we're already not using typebox, maybe there's a library that's significantly better for form validation than yup? We considered to to perform a more involved investigation concentrated on the frontend usecase, instead of quickly making a decision. But we don't feel like we have enough datapoints to make a decision now.

On the other hand, it doesn't seem very dangerous to keep using yup for this one purpose, maybe trying to use yup's infer functionality to better integrate with our current validation practice.

Consequences

We need to monitor for any cases of misunderstandings when using both yup and typebox. Also, any situations where we need to type/validate the same entity twice.

Related ADRs