zod icon indicating copy to clipboard operation
zod copied to clipboard

[Feature] Add phone number parsing

Open GustavoOS opened this issue 1 year ago • 4 comments

The idea is using a zod schema like z.string().phone() and let parse any phone number format valid world-wide.

GustavoOS avatar Apr 04 '24 11:04 GustavoOS

Super hard to do correctly. If someone wants to make a specific API proposal here, I'm all ears. But this is the kind of thing that's almost impossible to make everyone (or even most people) happy.

colinhacks avatar Apr 04 '24 21:04 colinhacks

Validation for E.164 phone numbers could be added via regex. It should validate most, albeit not all e164 numbers, correctly. See documentation from Twilio/Sendgrid: https://www.twilio.com/docs/glossary/what-e164#regex-matching-for-e164

Cheers

maurer2 avatar Apr 08 '24 21:04 maurer2

You can achieve this easily yourself with something like the following, and using libphonenumber-js at least somewhat guarantees good results:

import parsePhoneNumber from "libphonenumber-js";
import * as z from "zod";

/**
 * Zod schema that validates a phone number using `libphonenumber-js`.
 * Attempts to parse the provided value with a default country of `FI`.
 *
 * If the phone number is valid, the schema transforms the phone number into
 * an international format (e.g. `+358401234567`).
 */
export const zPhoneNumber = z.string().transform((value, ctx) => {
  const phoneNumber = parsePhoneNumber(value, {
    defaultCountry: "FI",
  });

  if (!phoneNumber?.isValid()) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      message: "Invalid phone number",
    });
    return z.NEVER;
  }

  return phoneNumber.formatInternational();
});

iffa avatar Apr 20 '24 07:04 iffa

At react-international-phone they recommend using google-libphonenumber for validation. Maybe Zod can rely on that for integrated phone validation as well?

jimmi-joensson avatar Aug 13 '24 07:08 jimmi-joensson