# AddressForm

`AddressForm` 组件提供了一个预构建的用户界面，用于收集账单地址信息。它与 `react-hook-form` 无缝集成，并包含针对邮政编码等字段的内置、特定国家/地区的验证。

该组件设计灵活，既支持完整的地址收集，也支持用于 Stripe 邮政编码验证的简化版本。

## Props

| Prop              | Type                               | Description                                                                                                                              | Default         |
| ----------------- | ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | --------------- |
| `mode`            | `string`                           | 决定要显示的字段。设置为 `'required'` 以显示完整的地址表单（地址行 1、城市、州/省、邮政编码、国家/地区）。       | `undefined`     |
| `stripe`          | `boolean`                          | 如果为 `true`，则显示一个仅包含邮政编码和国家/地区的简化表单，通常用于 Stripe 的银行卡验证。             | `false`         |
| `sx`              | `SxProps`                          | MUI 的 `sx` 属性，用于对根 `Stack` 组件进行自定义样式设置。                                                                        | `{}`            |
| `fieldValidation` | `Record<string, any>`              | 一个用于为特定字段提供自定义验证规则（例如正则表达式模式）的对象。有关详细信息，请参见验证部分。 | `{}`            |
| `errorPosition`   | `'right'` \| `'bottom'`             | 指定在输入字段的哪个位置显示验证错误消息。                                                      | `'right'`       |

## 用法

`AddressForm` 必须在 `react-hook-form` 的 `FormProvider` 中使用，因为它依赖其上下文来注册字段和管理状态。

### 标准账单地址

要收集完整的账单地址，请将 `mode` 属性设置为 `'required'`。这将渲染所有标准的地址字段，每个字段都带有“必填”验证规则。

```tsx AddressForm with Full Address icon=material-symbols:location-on-outline
import { FormProvider, useForm } from 'react-hook-form';
import { Button, Stack } from '@mui/material';
import AddressForm from './AddressForm'; // 调整导入路径

export default function FullAddressExample() {
  const methods = useForm({
    defaultValues: {
      billing_address: {
        line1: '',
        city: '',
        state: '',
        postal_code: '',
        country: 'US', // 默认国家/地区
      },
    },
  });

  const onSubmit = (data) => {
    console.log('表单数据：', data);
  };

  return (
    <FormProvider {...methods}>
      <form onSubmit={methods.handleSubmit(onSubmit)}>
        <Stack spacing={2}>
          <AddressForm mode="required" />
          <Button type="submit" variant="contained">
            Submit
          </Button>
        </Stack>
      </form>
    </FormProvider>
  );
}
```

此设置会渲染地址行、城市、州/省和邮政编码的输入字段。国家/地区通过集成的 [CountrySelect](./components-ui-form-elements-country-select.md) 组件进行选择。

### Stripe 邮政编码验证

在使用 Stripe 等支付方式时，通常只需要邮政编码和国家/地区进行银行卡验证。将 `stripe` 属性设置为 `true` 以渲染一个仅包含这两个字段的简化表单。

```tsx AddressForm for Stripe icon=logos:stripe
import { FormProvider, useForm } from 'react-hook-form';
import { Button, Stack } from '@mui/material';
import AddressForm from './AddressForm'; // 调整导入路径

export default function StripeAddressExample() {
  const methods = useForm({
    defaultValues: {
      billing_address: {
        postal_code: '',
        country: 'US', // 默认国家/地区
      },
    },
  });

  const onSubmit = (data) => {
    console.log('表单数据：', data);
  };

  return (
    <FormProvider {...methods}>
      <form onSubmit={methods.handleSubmit(onSubmit)}>
        <Stack spacing={2}>
          <AddressForm stripe={true} />
          <Button type="submit" variant="contained">
            Submit
          </Button>
        </Stack>
      </form>
    </FormProvider>
  );
}
```

## 验证

该组件包含对必填字段的自动验证。最显著的特点是动态邮政编码验证，它会根据所选的国家/地区调整其规则。

- **必填字段**：所有可见字段都会自动标记为必填。
- **邮政编码**：验证逻辑使用 `validator/lib/isPostalCode` 库。它会根据所选国家/地区的标准格式（例如，美国的 5 位数字，加拿大的字母数字组合）检查邮政编码格式。如果某个国家/地区的格式未被明确支持，则会应用通用验证。
- **自定义验证**：您可以通过 `fieldValidation` 属性传递额外的验证规则。例如，要对 `state` 字段强制执行特定模式：

```tsx
const customValidation = {
  'billing_address.state': {
    pattern: '^[A-Z]{2}$',
    pattern_message: {
      en: '州/省必须是 2 个字母的代码。',
    },
  },
};

<AddressForm mode="required" fieldValidation={customValidation} />;
```