-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
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
Comments
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. |
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 |
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();
}); |
The idea is using a zod schema like
z.string().phone()
and let parse any phone number format valid world-wide.
The text was updated successfully, but these errors were encountered: