Ensure optional routing number validation returns specific error messages

export const RoutingNumber = S.String.pipe(
  S.length(9, {
    message: () => 'Routing number must be 9 characters long'
  }),
  S.pattern(/^\d{9}$/, {
    message: () => 'Invalid routing number'
  }),
  S.brand("RoutingNumber")
);
export type RoutingNumber = typeof RoutingNumber.Type;
const InputRouting = S.optional(S.Union(RoutingNumber, S.Null))


I want to allow the routingNumber to be optional, but if there is data parsed and it does not meet the RoutingNumberrequirements, I want to show the messages from the RoutingNumber and not that Expected undefined, actual "111"

I have entered a string that does not meet the length of 9 and instead of returning the error Routing number must be 9 characters long, it is returning Expected undefined, actual "111".

NOTE: I am using the https://www.npmjs.com/package/@hookform/resolvers effect resolver

I understand that schema will return ALL errors in a union. Is it possible to reorder my const InputRouting = S.optional(S.Union(RoutingNumber, S.Null)) such that it will validate in the following order:
1. RoutingNumber
2. Null
3. optional

If this is possible, I can use the criteriaMode: 'firstError', in the hookform resolver

---

If I was to change it to const InputRouting = S.Union(RoutingNumber, S.Null, S.Undefined), I will still get the same error message that Expected undefined, actual "111".
Was this page helpful?