邮箱字段
Email 字段(Email Field)会强制要求提供的值是一个有效的电子邮件地址。


管理面板中的 Email 字段截图
要创建 Email 字段,需要在 Field Config 中将 type
设置为 email
:
import type { Field } from 'payload'
export const MyEmailField: Field = {
// ...
type: 'email', // highlight-line
}
配置选项
选项 | 描述 |
---|---|
name * | 作为属性名存储在数据库中并从数据库中检索时使用。了解更多 |
label | 在 Admin Panel 中用作字段标签的文本,或为每种语言提供键的对象。 |
unique | 强制 Collection 中每个条目对此字段具有唯一值。 |
index | 为此字段构建索引以加快查询速度。如果用户会频繁查询此字段的数据,请将此字段设置为 true 。 |
validate | 提供自定义验证函数,该函数将在 Admin Panel 和后端执行。了解更多 |
saveToJWT | 如果此字段是顶级字段且嵌套在支持身份验证的配置中,则将其数据包含在用户 JWT 中。 |
hooks | 提供字段钩子来控制此字段的逻辑。更多详情。 |
access | 提供字段访问控制,指定用户可以查看和操作此字段数据的权限。更多详情。 |
hidden | 完全限制此字段在所有 API 中的可见性。仍会保存到数据库,但不会出现在任何 API 或 Admin Panel 中。 |
defaultValue | 提供用于此字段默认值的数据。了解更多 |
localized | 为此字段启用本地化。需要在基础配置中启用本地化。 |
required | 要求此字段必须有值。 |
admin | 特定于 Admin 的配置。更多详情。 |
custom | 用于添加自定义数据(例如插件)的扩展点 |
typescriptSchema | 通过提供 JSON schema 来覆盖字段类型生成 |
virtual | 提供 true 以在数据库中禁用字段,或提供字符串路径以将字段与关系链接。参见虚拟字段 |
* 星号表示该属性是必填项。
管理选项
要自定义 Email Field 在管理面板中的外观和行为,可以使用 admin
选项:
import type { Field } from 'payload'
export const MyEmailField: Field = {
// ...
admin: {
// highlight-line
// ...
},
}
Email Field 继承了基础字段管理配置中的所有默认选项,并新增了以下额外选项:
属性 | 描述 |
---|---|
placeholder | 设置此属性可为字段定义占位文本。 |
autoComplete | 设置此属性将作为浏览器自动填充的提示字符串。 |
示例
collections/ExampleCollection.ts
import type { CollectionConfig } from 'payload'
export const ExampleCollection: CollectionConfig = {
slug: 'example-collection',
fields: [
{
name: 'contact', // 必填
type: 'email', // 必填
label: '联系邮箱地址',
required: true,
},
],
}
自定义组件
字段组件
服务端组件
import type React from 'react'
import { EmailField } from '@payloadcms/ui'
import type { EmailFieldServerComponent } from 'payload'
export const CustomEmailFieldServer: EmailFieldServerComponent = ({
clientField,
path,
schemaPath,
permissions,
}) => {
return (
<EmailField
field={clientField}
path={path}
schemaPath={schemaPath}
permissions={permissions}
/>
)
}
客户端组件
'use client'
import React from 'react'
import { EmailField } from '@payloadcms/ui'
import type { EmailFieldClientComponent } from 'payload'
export const CustomEmailFieldClient: EmailFieldClientComponent = (props) => {
return <EmailField {...props} />
}
标签组件
服务器组件
import React from 'react'
import { FieldLabel } from '@payloadcms/ui'
import type { EmailFieldLabelServerComponent } from 'payload'
export const CustomEmailFieldLabelServer: EmailFieldLabelServerComponent = ({
clientField,
path,
}) => {
return (
<FieldLabel
label={clientField?.label || clientField?.name}
path={path}
required={clientField?.required}
/>
)
}
客户端组件
'use client'
import React from 'react'
import { FieldLabel } from '@payloadcms/ui'
import type { EmailFieldLabelClientComponent } from 'payload'
export const CustomEmailFieldLabelClient: EmailFieldLabelClientComponent = ({
field,
path,
}) => {
return (
<FieldLabel
label={field?.label || field?.name}
path={path}
required={field?.required}
/>
)
}