Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature] Add phone number parsing #3378

Open
GustavoOS opened this issue Apr 4, 2024 · 3 comments
Open

[Feature] Add phone number parsing #3378

GustavoOS opened this issue Apr 4, 2024 · 3 comments

Comments

@GustavoOS
Copy link

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

@colinhacks
Copy link
Owner

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.

@maurer2
Copy link

maurer2 commented Apr 8, 2024

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

@iffa
Copy link

iffa commented Apr 20, 2024

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();
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants