Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 16 additions & 16 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
# Payload CMS Phone Number Plugin

[![Payload CMS](https://img.shields.io/badge/Payload%20CMS-v3-blue)](https://github.com/payloadcms/payload)
[![NPM Version](https://img.shields.io/npm/v/payload-phone-number-plugin)](https://www.npmjs.com/package/payload-phone-number-plugin)

This Payload CMS plugin uses [google-libphonenumber](https://github.com/ruimarinho/google-libphonenumber) to format and validate phone numbers.

![Preview](./src/assets/preview.png)

> Admin Panel screenshot of the Phone Number field

## Features

- Built with Payload UI components so it feels native to the Admin UI
- As-you-type formatting
- Validates server-side and client-side
- Support for limiting to only some countries
- Format phone numbers to multiple formats (E.164, national, international)
- As-you-type formatting based on selected country
- Validates phone numbers based on selected country
- Support for limiting selection to only some countries
- Support for setting a default country
- Automatic formatting and region detection when pasting phone numbers
- Automatic formatting and region detection when pasting international phone numbers
- Full TypeScript support with generated phone number types
- Built with Payload UI components so it feels native to the Admin Panel
- i18n support for validation messages (PRs for new languages are welcome)

## Installation
Expand Down Expand Up @@ -89,7 +89,7 @@ phoneNumberField({
```ts
phoneNumberField({
name: 'phoneNumber',
label: 'Phone Phone',
label: 'Phone Number',
defaultCountry: 'NO', // Norway will be pre-selected
allowedCountries: ['NO', 'US', 'SE'], // Only these countries will be selectable
})
Expand All @@ -107,9 +107,9 @@ phoneNumberField({
})
```

## Creating Records Programmatically
## Creating Documents Programmatically

When creating or updating records, pass the phone number as an E.164 string directly.
When creating or updating documents, pass the phone number as an E.164 string directly. Phone numbers are stored in E.164 format in the database.

The field will handle parsing and validation so it won't save unless it's a valid phone number for that field.

Expand Down Expand Up @@ -139,11 +139,11 @@ await fetch('http://localhost:3000/api/employees', {
> [!NOTE]
> You cannot pass a phone number object, only E.164 strings are accepted.

## Querying Phone Numbers by Where
## Querying by Phone Number

When using `payload.find` or database queries, use the E.164 format since phone numbers are stored as E.164 strings:
When using `payload.find` or database queries, use the E.164 format:

```typescript
```ts
const employees = await payload.find({
collection: 'employees',
where: {
Expand All @@ -158,7 +158,7 @@ The same applies when using the REST API.

## TypeScript Types

The plugin uses a union type pattern similar to Payload's relationship fields with depth. The field is typed as `string | PhoneNumber`.
The field is typed as `string | PhoneNumber`, similar to Payload's relationship fields with depth.

This is because phone numbers are stored as strings in the database but are transformed into objects when you read them using libphonenumber.

Expand Down Expand Up @@ -192,6 +192,6 @@ Example response:

## Additional Information

A region code is a ISO 3166-1 alpha-2 code.
A region code is an ISO 3166-1 alpha-2 code.

List of all valid region codes can be found here: https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2#Officially_assigned_code_elements
1 change: 1 addition & 0 deletions src/defaults.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ import type { Defaults } from './types.js';

export const defaults: Defaults = {
defaultCountry: 'US',
cellDisplayFormat: 'international',
};
12 changes: 12 additions & 0 deletions src/translations/da.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import type { GenericTranslationsObject } from '@payloadcms/translations';

export const da: GenericTranslationsObject = {
$schema: './translation-schema.json',
'payload-phone-number-plugin': {
phoneNumberRequired: 'Telefonnummer er påkrævet',
invalidPhoneNumber: 'Ugyldigt telefonnummer',
invalidPhoneNumberFormat: 'Ugyldigt telefonnummerformat for landet',
phoneNumberMustBeString: 'Telefonnummer skal være en tekststreng',
phoneNumberCountryNotAllowed: 'Telefonnummer skal være fra et af de tilladte lande',
},
};
4 changes: 4 additions & 0 deletions src/translations/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,14 @@ import type { GenericTranslationsObject, NestedKeysStripped } from '@payloadcms/

import { en } from './en.js';
import { nb } from './nb.js';
import { sv } from './sv.js';
import { da } from './da.js';

export const translations = {
en,
nb,
sv,
da,
};

export type PayloadPhoneNumberPluginTranslations = GenericTranslationsObject;
Expand Down
12 changes: 12 additions & 0 deletions src/translations/sv.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import type { GenericTranslationsObject } from '@payloadcms/translations';

export const sv: GenericTranslationsObject = {
$schema: './translation-schema.json',
'payload-phone-number-plugin': {
phoneNumberRequired: 'Telefonnummer krävs',
invalidPhoneNumber: 'Ogiltigt telefonnummer',
invalidPhoneNumberFormat: 'Ogiltigt telefonnummerformat för landet',
phoneNumberMustBeString: 'Telefonnummer måste vara en textsträng',
phoneNumberCountryNotAllowed: 'Telefonnummer måste vara från ett av de tillåtna länderna',
},
};
7 changes: 7 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,14 @@ export type Country = {
};

export type Defaults = {
/**
* @default 'US'
*/
defaultCountry: RegionCode;
/**
* @default 'international'
*/
cellDisplayFormat: CellDisplayFormat;
};

export type { RegionCode };
3 changes: 2 additions & 1 deletion src/ui/Cell/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,13 @@ import { useTranslation } from '@payloadcms/ui';
import type { FC } from 'react';

import type { PhoneNumberValue, CellDisplayFormat } from '../../types.js';
import { defaults } from '../../defaults.js';

type PhoneNumberCellProps = DefaultCellComponentProps<TextFieldClient, PhoneNumberValue> & {
cellDisplayFormat?: CellDisplayFormat;
};

export const PhoneNumberCellComponent: FC<PhoneNumberCellProps> = ({ cellData, cellDisplayFormat = 'international', field }) => {
export const PhoneNumberCellComponent: FC<PhoneNumberCellProps> = ({ cellData, cellDisplayFormat = defaults.cellDisplayFormat, field }) => {
const { i18n } = useTranslation();

if (cellData && typeof cellData === 'object' && 'international' in cellData) {
Expand Down
2 changes: 1 addition & 1 deletion src/ui/Field/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ type PhoneNumberFieldProps = {
} & TextFieldClientProps;

const countryOptions: OptionObject[] = countries.map((country) => ({
label: `${country.emoji} ${country.callingCode} (${country.name.international})`,
label: `${country.name.international} (${country.callingCode})`,
value: country.regionCode,
}));

Expand Down
4 changes: 0 additions & 4 deletions src/utilities/countries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1964,9 +1964,5 @@ const allCountries: Record<RegionCode, Country> = {
};

export const countries = Object.values(allCountries).sort((a, b) => {
const numA = Number(String(a.callingCode).replace('+', ''));
const numB = Number(String(b.callingCode).replace('+', ''));
if (numA !== numB) return numA - numB;

return a.name.international.localeCompare(b.name.international);
});