> ## Documentation Index
> Fetch the complete documentation index at: https://primer.io/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# usePrimerCardForm

> Hook that reads and updates the card form: field values, validation, network traits and submission.

> [!WARNING]
>
> Primer Checkout React Native SDK is currently in **beta** (v3.0.0-beta.1).
> The API is subject to change before the stable release.

`usePrimerCardForm` gives your components the card form state held by [`PrimerCardFormProvider`](https://primer.io/docs/sdk/react-native-checkout/v3.0.0-beta/api/card-form/primer-card-form#primercardformprovider): field values, update functions, validation errors, the detected network's traits and `submit()`. The card inputs and `PrimerCardForm` use it internally. Call it yourself for a Pay button, your own fields or your own error messages.

## Signature

```tsx theme={"dark"}
function usePrimerCardForm(options?: UseCardFormOptions): UsePrimerCardFormReturn;
```

Call it in a component below `PrimerCardFormProvider`, which sits inside `PrimerCheckoutProvider`. Without `PrimerCardFormProvider` it throws an error that starts with `usePrimerCardForm must be used within a <PrimerCardFormProvider>.`

Every caller below the same provider reads and writes the same state. The options apply only to the caller that passes them.

## Options

| Prop | Type | Default | Description |
| - | - | - | - |
| `onValidationChange` | `(isValid: boolean, errors: CardFormErrors) => void` | — | Called once after mount and again whenever `isValid` or `errors` change. `errors` is the set of messages shown right now (see [When errors show](#when-errors-show)). |
| `onBinDataChange` | `(binData: BinData) => void` | — | Called when the native SDK reports new BIN data for the card number. See [`BinData`](https://primer.io/docs/sdk/react-native-checkout/v3.0.0-beta/api/card-form/card-networks#bindata). |
| `onMetadataChange` | `(metadata: any) => void` | — | Called when the native SDK reports new card metadata. |

The hook keeps the latest callbacks in refs, so passing a new function on every render doesn't cause extra calls.

## Returns

### Field values

| Field | Type | Description |
| - | - | - |
| `cardNumber` | `string` | The card number as shown, with spaces from the network's gap pattern, for example `4242 4242 4242 4242`. |
| `expiryDate` | `string` | The expiry date as `MM/YY` once two or more digits are entered. While the shopper deletes, it holds the digits without the `/`. |
| `cvv` | `string` | The security code, digits only. |
| `cardholderName` | `string` | The cardholder name as typed. |

### Update functions

| Method | Description |
| - | - |
| `updateCardNumber(value: string)` | Keeps the digits, cuts them to the longest card number of the detected network, and inserts spaces. |
| `updateExpiryDate(value: string)` | Keeps up to four digits and inserts `/` after the month. When the new value is shorter than the old one, for example while the shopper deletes, it returns the digits without the `/`. |
| `updateCVV(value: string)` | Keeps the digits, up to the network's CVV length (3 or 4). |
| `updateCardholderName(value: string)` | Stores the value unchanged. |

When the detected network changes, the SDK reformats the card number for the new network and cuts digits beyond its longest length.

### Validation state

| Field | Type | Description |
| - | - | - |
| `isValid` | `boolean` | `true` when the native SDK reports the card data as valid. It doesn't depend on which errors are shown. |
| `errors` | `CardFormErrors` | The error message of each card field that should show one now. |
| `submitAttempted` | `boolean` | `true` after `submit()` or `markSubmitAttempted()`, until `reset()`. |

| Method | Description |
| - | - |
| `markFieldFocused(field: CardFormField)` | Call when your own field gets focus. Focusing a field doesn't hide its error. |
| `markFieldBlurred(field: CardFormField)` | Call when your own field loses focus. Shows that field's error, if it has one, the field holds a value, and you called `markFieldFocused` for it first. Call both, or the error stays hidden until a submit attempt. |
| `markSubmitAttempted()` | Shows the error of every card field. `submit()` calls it for you. |

### Submission state

| Field | Type | Description |
| - | - | - |
| `isSubmitting` | `boolean` | `true` while `submit()` hands the card to the native SDK. |

| Method | Description |
| - | - |
| `submit(): Promise<void>` | Submits the card. See [How submit works](#how-submit-works). Never rejects. |
| `reset()` | Clears the four fields, the focus and submit flags, and sends empty card data to the native SDK. |

### Card details

| Field | Type | Description |
| - | - | - |
| `binData` | `BinData \| null` | The BIN data the native SDK reports for the card number, or `null`. See [`BinData`](https://primer.io/docs/sdk/react-native-checkout/v3.0.0-beta/api/card-form/card-networks#bindata). |
| `descriptor` | object | Traits of the detected network. See [Network descriptor](#network-descriptor). |
| `cardNumberMaxLength` | `number` | The longest formatted card number for the network: digits plus spaces. Use it as `maxLength` on your own card number input. |
| `requiredFields` | `InputElementType[]` | The card fields the native SDK requires for the session, for example `InputElementType.CARD_NUMBER`. Empty until the card form is active. |
| `isCardholderNameVisible` | `boolean` | `false` only when the client session's `CARD_INFORMATION` checkout module turns off the cardholder name. Hide your cardholder name field when it is `false`. |

### Network descriptor

`descriptor` describes the detected network. The SDK uses it to format the card number and to size and label the CVV field.

| Field | Type | Description |
| - | - | - |
| `id` | `CardNetworkId` | The network identifier, for example `'VISA'`. See [`CardNetworkId`](https://primer.io/docs/sdk/react-native-checkout/v3.0.0-beta/api/card-form/card-networks#cardnetworkid). |
| `displayName` | `string` | The network name, for example `"American Express"`. |
| `panLengths` | `readonly number[]` | The valid card number lengths, in digits. |
| `gapPattern` | `readonly number[]` | The digit positions before which a space goes. `[4, 8, 12]` gives `4242 4242 4242 4242`. |
| `cvvLength` | `3 \| 4` | The number of CVV digits. |
| `cvvLabel` | `'CVV' \| 'CVC' \| 'CID' \| 'CVN' \| 'CVE' \| 'CVP2'` | The name of the security code on the card. |

Until a network is detected, and when the native SDK has no traits for it, `descriptor` holds the default:

```tsx theme={"dark"}
{
  id: 'OTHER',
  displayName: 'Card',
  panLengths: [16, 17, 18, 19],
  gapPattern: [4, 8, 12],
  cvvLength: 3,
  cvvLabel: 'CVV',
}
```

### Types

```tsx theme={"dark"}
type CardFormField = 'cardNumber' | 'expiryDate' | 'cvv' | 'cardholderName';
type CardFormErrors = Partial<Record<CardFormField, string>>;
```

Exported types: `UseCardFormOptions`, `UsePrimerCardFormReturn`, `CardFormField`, `CardFormErrors`.

## When errors show

The native SDK validates the card data. The hook decides which messages to show:

* A field's error appears in `errors` after the shopper focuses the field and leaves it with a value in it. The error stays, also while the shopper edits the field again, until the value is valid. An empty field shows no error.
* After a submit attempt, every card field with an error shows it, empty fields included. This lasts until `reset()`.
* `isValid` doesn't depend on which errors are shown. Gate your Pay button on it.
* The messages come from the native SDK. `errors` only has entries for the four card fields.

The SDK inputs call `markFieldFocused` and `markFieldBlurred` for you. Call them yourself only for fields you build.

## How submit works

`submit()` runs these steps:

1. It marks the submit as attempted, so every error shows.
2. It stops when the provider isn't ready, the card form isn't active, or a submit is already running.
3. It sends any pending field changes to the native SDK.
4. It stops when `isValid` is `false`.
5. It hands the card to the native SDK, which tokenizes it and creates the payment.

`submit()` never rejects. Read the result from [`usePrimerCheckout().paymentOutcome`](https://primer.io/docs/sdk/react-native-checkout/v3.0.0-beta/api/use-primer-checkout).

The card form is active after you call `start()` on [`usePrimerPaymentMethod('PAYMENT_CARD')`](https://primer.io/docs/sdk/react-native-checkout/v3.0.0-beta/api/payment-methods/use-primer-payment-method). Until then the SDK validates nothing and `isValid` stays `false`.

## Examples

### Pay button

```tsx theme={"dark"}
import { useEffect } from 'react';
import { Button, Text, View } from 'react-native';
import { usePrimerCardForm, usePrimerCheckout } from '@primer-io/react-native';

function PayButton({ onTryAgain }: { onTryAgain: () => void }) {
  const cardForm = usePrimerCardForm();
  const { paymentOutcome } = usePrimerCheckout();

  useEffect(() => {
    if (paymentOutcome?.status === 'error') {
      const { errorId, description, diagnosticsId } = paymentOutcome.error;
      console.warn(`[${errorId}] ${description}`, { diagnosticsId });
    }
  }, [paymentOutcome]);

  if (paymentOutcome?.status === 'error') {
    return (
      <View>
        <Text>The payment failed. Try again or use another card.</Text>
        <Button title="Try again" onPress={onTryAgain} />
      </View>
    );
  }

  return (
    <Button
      title="Pay"
      disabled={!cardForm.isValid || cardForm.isSubmitting}
      onPress={() => cardForm.submit()}
    />
  );
}
```

To guard Pay, set your own paying flag on the tap and clear it only if the payment fails, as in [Disable buttons during payment](https://primer.io/docs/checkout/primer-checkout/guides-and-recipes/disable-buttons-during-payment.md).

`error.description` is for your logs. Show the shopper your own message. See [`PrimerError`](https://primer.io/docs/sdk/react-native-checkout/v3.0.0-beta/api/common/primer-error).

### Your own field

Build a field with [`PrimerTextInput`](https://primer.io/docs/sdk/react-native-checkout/v3.0.0-beta/api/card-form/card-inputs#primertextinput) and wire it to the hook. Pass the value, the updater, the focus calls and the error:

```tsx theme={"dark"}
import { PrimerTextInput, usePrimerCardForm } from '@primer-io/react-native';

function CardholderNameField() {
  const cardForm = usePrimerCardForm();

  if (!cardForm.isCardholderNameVisible) return null;

  return (
    <PrimerTextInput
      label="Name on card"
      value={cardForm.cardholderName}
      onChangeText={cardForm.updateCardholderName}
      onFocus={() => cardForm.markFieldFocused('cardholderName')}
      onBlur={() => cardForm.markFieldBlurred('cardholderName')}
      error={cardForm.errors.cardholderName}
      autoCapitalize="words"
      autoComplete="name"
    />
  );
}
```

## See also

> [card] [PrimerCardForm](https://primer.io/docs/sdk/react-native-checkout/v3.0.0-beta/api/card-form/primer-card-form.md)
>
> The card fields in a fixed layout, and `PrimerCardFormProvider`.

> [card] [Card inputs](https://primer.io/docs/sdk/react-native-checkout/v3.0.0-beta/api/card-form/card-inputs.md)
>
> The individual card fields and `PrimerTextInput`.

> [card] [Card networks](https://primer.io/docs/sdk/react-native-checkout/v3.0.0-beta/api/card-form/card-networks.md)
>
> `BinData`, the detected network and co-badged selection.

> [card] [usePrimerCheckout](https://primer.io/docs/sdk/react-native-checkout/v3.0.0-beta/api/use-primer-checkout.md)
>
> `paymentOutcome` and the rest of the checkout state.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.