<input type="email">

email 类型的 <input> 元素用于让用户输入和编辑电子邮件地址,或者,如果指定了 multiple 属性,则输入和编辑电子邮件地址列表。

¥<input> elements of type email are used to let the user enter and edit an email address, or, if the multiple attribute is specified, a list of email addresses.

Try it

在提交表单之前,系统会自动验证输入值,以确保其为空或格式正确的电子邮件地址(或地址列表)。:valid:invalid CSS 伪类会根据需要自动应用,以直观地指示字段的当前值是否是有效的电子邮件地址。

¥The input value is automatically validated to ensure that it's either empty or a properly-formatted email address (or list of addresses) before the form can be submitted. The :valid and :invalid CSS pseudo-classes are automatically applied as appropriate to visually denote whether the current value of the field is a valid email address or not.

¥Value

<input> 元素的 value 属性包含一个字符串,该字符串会自动验证为符合电子邮件语法。更具体地说,三种可能的值格式将通过验证:

¥The <input> element's value attribute contains a string which is automatically validated as conforming to email syntax. More specifically, there are three possible value formats that will pass validation:

  1. 空字符串 ("") 指示用户未输入值或该值已被删除。
  2. 一个格式正确的电子邮件地址。这并不一定意味着电子邮件地址存在,但至少格式正确。简单来说,这意味着 username@domainusername@domain.tld。当然,事情远不止这些。请参阅 验证 了解与电子邮件地址验证算法匹配的 regular expression
  3. 当且仅当指定了 multiple 属性时,该值可以是格式正确、以逗号分隔的电子邮件地址的列表。列表中每个地址的任何尾随和前导空格都会被删除。

有关如何验证电子邮件地址以确保其格式正确的详细信息,请参阅 验证

¥See Validation for details on how email addresses are validated to ensure that they're formatted properly.

附加属性

¥Additional attributes

除了对所有 <input> 元素(无论其类型如何)进行操作的属性之外,email 输入还支持以下属性。

¥In addition to the attributes that operate on all <input> elements regardless of their type, email inputs support the following attributes.

list

列表属性的值是位于同一文档中的 <datalist> 元素的 id<datalist> 提供了一个预定义值列表来建议用户进行此输入。列表中与 type 不兼容的任何值都不包含在建议选项中。提供的值是建议,而不是要求:用户可以从此预定义列表中进行选择或提供不同的值。

¥The values of the list attribute is the id of a <datalist> element located in the same document. The <datalist> provides a list of predefined values to suggest to the user for this input. Any values in the list that are not compatible with the type are not included in the suggested options. The values provided are suggestions, not requirements: users can select from this predefined list or provide a different value.

maxlength

用户可以在 email 输入中输入的最大字符串长度(以 UTF-16 代码单元测量)。这必须是 0 或更大的整数值。如果未指定 maxlength,或指定了无效值,则 email 输入没有最大长度。该值还必须大于或等于 minlength 的值。

¥The maximum string length (measured in UTF-16 code units) that the user can enter into the email input. This must be an integer value of 0 or higher. If no maxlength is specified, or an invalid value is specified, the email input has no maximum length. This value must also be greater than or equal to the value of minlength.

如果字段文本值的长度大于 maxlength UTF-16 代码单元长,则输入将失败 约束验证。仅当用户更改值时才应用约束验证。

¥The input will fail constraint validation if the length of the text value of the field is greater than maxlength UTF-16 code units long. Constraint validation is only applied when the value is changed by the user.

minlength

用户可以在 email 输入中输入的最小字符串长度(以 UTF-16 代码单位测量)。该值必须是小于或等于 maxlength 指定值的非负整数值。如果未指定 minlength,或者指定了无效值,则 email 输入没有最小长度。

¥The minimum string length (measured in UTF-16 code units) that the user can enter into the email input. This must be a non-negative integer value smaller than or equal to the value specified by maxlength. If no minlength is specified, or an invalid value is specified, the email input has no minimum length.

如果输入字段的文本长度小于 minlength UTF-16 代码单元长度,则输入将失败 约束验证。仅当用户更改值时才应用约束验证。

¥The input will fail constraint validation if the length of the text entered into the field is fewer than minlength UTF-16 code units long. Constraint validation is only applied when the value is changed by the user.

multiple

布尔属性,如果存在,则指示用户可以输入多个电子邮件地址的列表,以逗号和可选的空格字符分隔。请参阅 允许多个电子邮件地址 作为示例,或参见 HTML 属性:multiple 了解更多详细信息。

¥A Boolean attribute which, if present, indicates that the user can enter a list of multiple email addresses, separated by commas and, optionally, whitespace characters. See Allowing multiple email addresses for an example, or HTML attribute: multiple for more details.

注意:通常,如果你指定 required 属性,则用户必须输入有效的电子邮件地址,该字段才会被视为有效。但是,如果你添加 multiple 属性,则零个电子邮件地址列表(空字符串或完全是空格的字符串)是有效值。换句话说,当指定 multiple 时,无论 required 的值如何,用户都不必输入一个电子邮件地址。

¥Note: Normally, if you specify the required attribute, the user must enter a valid email address for the field to be considered valid. However, if you add the multiple attribute, a list of zero email addresses (an empty string, or one which is entirely whitespace) is a valid value. In other words, the user does not have to enter even one email address when multiple is specified, regardless of the value of required.

pattern

指定时,pattern 属性是一个正则表达式,输入的 value 必须与该正则表达式匹配才能传递 约束验证 的值。它必须是有效的 JavaScript 正则表达式,如 RegExp 类型所使用的,以及我们的 正则表达式指南 中记录的;编译正则表达式时指定 'u' 标志,以便将模式视为 Unicode 代码点序列,而不是 ASCII。模式文本周围不应指定正斜杠。

¥The pattern attribute, when specified, is a regular expression that the input's value must match for the value to pass constraint validation. It must be a valid JavaScript regular expression, as used by the RegExp type, and as documented in our guide on regular expressions; the 'u' flag is specified when compiling the regular expression so that the pattern is treated as a sequence of Unicode code points, instead of as ASCII. No forward slashes should be specified around the pattern text.

如果指定的模式未指定或无效,则不应用正则表达式,并且完全忽略该属性。

¥If the specified pattern is not specified or is invalid, no regular expression is applied and this attribute is ignored completely.

注意:使用 title 属性指定大多数浏览器将显示为工具提示的文本,以解释匹配模式的要求。你还应该在附近添加其他解释性文字。

¥Note: Use the title attribute to specify text that most browsers will display as a tooltip to explain what the requirements are to match the pattern. You should also include other explanatory text nearby.

有关详细信息和示例,请参阅第 模式验证 节。

¥See the section Pattern validation for details and an example.

placeholder

placeholder 属性是一个字符串,向用户提供有关该字段中期望的信息类型的简短提示。它应该是一个单词或短语,展示预期的数据类型,而不是解释性消息。文本不得包含回车或换行。

¥The placeholder attribute is a string that provides a brief hint to the user as to what kind of information is expected in the field. It should be a word or short phrase that demonstrates the expected type of data, rather than an explanatory message. The text must not include carriage returns or line feeds.

如果控件的内容具有一个方向性(LTRRTL),但需要以相反的方向性呈现占位符,则可以使用 Unicode 双向算法格式化字符来覆盖占位符内的方向性;请参阅 如何使用 Bidi 文本的 Unicode 控件 了解更多信息。

¥If the control's content has one directionality (LTR or RTL) but needs to present the placeholder in the opposite directionality, you can use Unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see How to use Unicode controls for bidi text for more information.

注意:如果可以的话,请避免使用 placeholder 属性。它在语义上不如解释表单的其他方法那么有用,并且可能会导致内容出现意外的技术问题。请参阅 <input> 标签 了解更多信息。

¥Note: Avoid using the placeholder attribute if you can. It is not as semantically useful as other ways to explain your form, and can cause unexpected technical issues with your content. See <input> labels for more information.

readonly

布尔属性,如果存在,则意味着用户无法编辑该字段。然而,它的 value 仍然可以通过 JavaScript 代码直接设置 HTMLInputElement value 属性来更改。

¥A Boolean attribute which, if present, means this field cannot be edited by the user. Its value can, however, still be changed by JavaScript code directly setting the HTMLInputElement value property.

注意:由于只读字段不能有值,因此 required 对同时指定了 readonly 属性的输入没有任何影响。

¥Note: Because a read-only field cannot have a value, required does not have any effect on inputs with the readonly attribute also specified.

size

size 属性是一个数值,指示输入字段应有多少个字符宽。该值必须是大于零的数字,默认值为 20。由于字符宽度各不相同,因此这可能准确,也可能不准确,因此不应依赖于此;结果输入可能比指定的字符数更窄或更宽,具体取决于字符和字体(使用的 font 设置)。

¥The size attribute is a numeric value indicating how many characters wide the input field should be. The value must be a number greater than zero, and the default value is 20. Since character widths vary, this may or may not be exact and should not be relied upon to be so; the resulting input may be narrower or wider than the specified number of characters, depending on the characters and the font (font settings in use).

这不会限制用户可以在该字段中输入的字符数。它仅指定一次大约可以看到多少个。要设置输入数据长度的上限,请使用 maxlength 属性。

¥This does not set a limit on how many characters the user can enter into the field. It only specifies approximately how many can be seen at a time. To set an upper limit on the length of the input data, use the maxlength attribute.

使用电子邮件输入

¥Using email inputs

电子邮件地址是网络上最常输入的文本数据形式之一;它们在登录网站、请求信息、允许订单确认、网络邮件等时使用。因此,email 输入类型可以使你作为 Web 开发者的工作变得更加轻松,因为它可以帮助简化你在构建电子邮件地址的用户界面和逻辑时的工作。当你使用正确的 typeemail 创建电子邮件输入时,你会自动验证输入的文本至少采用正确的形式,可能是合法的电子邮件地址。这有助于避免用户输入错误地址或提供无效地址的情况。

¥Email addresses are among the most frequently-inputted textual data forms on the web; they're used when logging into websites, when requesting information, to allow order confirmation, for webmail, and so forth. As such, the email input type can make your job as a web developer much easier since it can help simplify your work when building the user interface and logic for email addresses. When you create an email input with the proper type value, email, you get automatic validation that the entered text is at least in the correct form to potentially be a legitimate email address. This can help avoid cases in which the user mistypes their address, or provides an invalid address.

然而,值得注意的是,这不足以确保指定的文本是实际存在的、与网站用户相对应的或以任何其他方式可接受的电子邮件地址。它确保字段值的格式正确为电子邮件地址。

¥It's important, however, to note that this is not enough to ensure that the specified text is an email address which actually exists, corresponds to the user of the site, or is acceptable in any other way. It ensures that the value of the field is properly formatted to be an email address.

注意:同样重要的是要记住,用户可以在幕后修改你的 HTML,因此你的网站不得出于任何安全目的使用此验证。你必须在任何交易的服务器端验证电子邮件地址,其中所提供的文本可能具有任何类型的安全隐患。

¥Note: It's also crucial to remember that a user can tinker with your HTML behind the scenes, so your site must not use this validation for any security purposes. You must verify the email address on the server side of any transaction in which the provided text may have any security implications of any kind.

简单的电子邮件输入

¥A simple email input

目前,所有实现此元素的浏览器都将其实现为具有基本验证功能的标准文本输入字段。然而,该规范确实允许浏览器在这方面有一定的自由度。例如,该元素可以与用户设备的内置地址簿集成,以允许从该列表中选择电子邮件地址。在最基本的形式中,email 输入可以这样实现:

¥Currently, all browsers which implement this element implement it as a standard text input field with basic validation features. The specification does, however, allow browsers latitude on this. For example, the element could be integrated with the user's device's built-in address book to allow picking email addresses from that list. In its most basic form, an email input can be implemented like this:

html
<input id="emailAddress" type="email" />

请注意,当为空且输入单个格式有效的电子邮件地址时,它被视为有效,但在其他情况下则不被视为有效。通过添加 required 属性,仅允许格式有效的电子邮件地址;输入为空时不再被视为有效。

¥Notice that it's considered valid when empty and when a single validly-formatted email address is entered, but is otherwise not considered valid. By adding the required attribute, only validly-formed email addresses are allowed; the input is no longer considered valid when empty.

允许多个电子邮件地址

¥Allowing multiple email addresses

通过添加 multiple 布尔属性,可以将输入配置为接受多个电子邮件地址。

¥By adding the multiple Boolean attribute, the input can be configured to accept multiple email addresses.

html
<input id="emailAddress" type="email" multiple />

现在,当输入单个电子邮件地址时,或者当任意数量的由逗号分隔的电子邮件地址以及(可选)存在一定数量的空白字符时,输入被视为有效。

¥The input is now considered valid when a single email address is entered, or when any number of email addresses separated by commas and, optionally, some number of whitespace characters are present.

注意:当使用 multiple 时,该值允许为空。

¥Note: When multiple is used, the value is allowed to be empty.

指定 multiple 时有效字符串的一些示例:

¥Some examples of valid strings when multiple is specified:

  • ""
  • "me@example"
  • "me@example.org"
  • "me@example.org,you@example.org"
  • "me@example.org, you@example.org"
  • "me@example.org,you@example.org, us@example.org"

无效字符串的一些示例:

¥Some examples of invalid strings:

  • ","
  • "me"
  • "me@example.org you@example.org"

占位符

¥Placeholders

有时,提供有关输入数据应采用什么形式的上下文提示会很有帮助。如果页面设计没有为每个 <input> 提供描述性标签,这一点尤其重要。这就是占位符发挥作用的地方。占位符是一个值,通过提供有效值的示例来演示 value 应采用的形式,当元素的 value 为 "" 时,该值将显示在编辑框中。一旦数据输入到框中,占位符就会消失;如果该框被清空,则占位符会重新出现。

¥Sometimes it's helpful to offer an in-context hint as to what form the input data should take. This can be especially important if the page design doesn't offer descriptive labels for each <input>. This is where placeholders come in. A placeholder is a value that demonstrates the form the value should take by presenting an example of a valid value, which is displayed inside the edit box when the element's value is "". Once data is entered into the box, the placeholder disappears; if the box is emptied, the placeholder reappears.

在这里,我们有一个带有占位符 sophie@example.comemail 输入。请注意当你操作编辑字段的内容时占位符如何消失和重新出现。

¥Here, we have an email input with the placeholder sophie@example.com. Note how the placeholder disappears and reappears as you manipulate the contents of the edit field.

html
<input type="email" placeholder="sophie@example.com" />

控制输入大小

¥Controlling the input size

你不仅可以控制输入框的物理长度,还可以控制输入文本本身允许的最小和最大长度。

¥You can control not only the physical length of the input box, but also the minimum and maximum lengths allowed for the input text itself.

物理输入元素大小

¥Physical input element size

输入框的物理尺寸可以使用 size 属性来控制。使用它,你可以指定输入框一次可以显示的字符数。在此示例中,email 编辑框的宽度为 15 个字符:

¥The physical size of the input box can be controlled using the size attribute. With it, you can specify the number of characters the input box can display at a time. In this example the email edit box is 15 characters wide:

html
<input type="email" size="15" />

元素值长度

¥Element value length

size 与输入的电子邮件地址本身的长度限制无关,因此你可以将字段容纳在较小的空间中,同时仍然允许输入更长的电子邮件地址字符串。你可以使用 minlength 属性指定输入的电子邮件地址的最小长度(以字符为单位);同样,使用 maxlength 设置输入的电子邮件地址的最大长度。

¥The size is separate from the length limitation on the entered email address itself so that you can have fields fit in a small space while still allowing longer email address strings to be entered. You can specify a minimum length, in characters, for the entered email address using the minlength attribute; similarly, use maxlength to set the maximum length of the entered email address.

下面的示例创建了一个 32 个字符宽的电子邮件地址输入框,要求内容不少于 3 个字符且不超过 64 个字符。

¥The example below creates a 32 character-wide email address entry box, requiring that the contents be no shorter than 3 characters and no longer than 64 characters.

html
<input type="email" size="32" minlength="3" maxlength="64" />

提供默认选项

¥Providing default options

使用 value 属性提供单个默认值

¥Providing a single default using the value attribute

与往常一样,你可以通过设置 value 属性来为 email 输入框提供默认值:

¥As always, you can provide a default value for an email input box by setting its value attribute:

html
<input type="email" value="default@example.com" />

提供建议值

¥Offering suggested values

更进一步,你可以提供默认选项列表,用户可以通过指定 list 属性从中进行选择。这并不限制用户使用这些选项,而是允许他们更快地选择常用的电子邮件地址。这也给 autocomplete 提供了提示。list 属性指定 <datalist> 的 ID,而 <datalist> 又包含每个建议值一个 <option> 元素;每个 optionvalue 是电子邮件输入框对应的建议值。

¥Taking it a step further, you can provide a list of default options from which the user can select by specifying the list attribute. This doesn't limit the user to those options, but does allow them to select commonly-used email addresses more quickly. This also offers hints to autocomplete. The list attribute specifies the ID of a <datalist>, which in turn contains one <option> element per suggested value; each option's value is the corresponding suggested value for the email entry box.

html
<input type="email" size="40" list="defaultEmails" />

<datalist id="defaultEmails">
  <option value="jbond007@mi6.defence.gov.uk"></option>
  <option value="jbourne@unknown.net"></option>
  <option value="nfury@shield.org"></option>
  <option value="tony@starkindustries.com"></option>
  <option value="hulk@grrrrrrrr.arg"></option>
</datalist>

<datalist> 元素及其 <option> 就位后,浏览器将提供指定的值作为电子邮件地址的潜在值;这通常显示为包含建议的弹出或下拉菜单。虽然特定的用户体验可能因浏览器而异,但通常单击编辑框会显示建议电子邮件地址的下拉菜单。然后,当用户键入时,列表将被过滤以仅显示匹配的值。每个键入的字符都会缩小列表范围,直到用户做出选择或键入自定义值。

¥With the <datalist> element and its <option>s in place, the browser will offer the specified values as potential values for the email address; this is typically presented as a popup or drop-down menu containing the suggestions. While the specific user experience may vary from one browser to another, typically clicking in the edit box presents a drop-down of the suggested email addresses. Then, as the user types, the list is filtered to show only matching values. Each typed character narrows down the list until the user makes a selection or types a custom value.

验证

¥Validation

email 输入可使用两个级别的内容验证。首先,向所有 <input> 提供标准级别的验证,自动确保内容满足有效电子邮件地址的要求。但还可以选择添加额外的过滤,以确保满足你自己的特殊需求(如果有)。

¥There are two levels of content validation available for email inputs. First, there's the standard level of validation offered to all <input>s, which automatically ensures that the contents meet the requirements to be a valid email address. But there's also the option to add additional filtering to ensure that your own specialized needs are met, if you have any.

警告:HTML 表单验证并不能替代确保输入数据采用正确格式的脚本。对于某些人来说,对 HTML 进行调整以绕过验证或完全删除验证太容易了。其他人也有可能完全绕过你的 HTML 并将数据直接提交到你的服务器。如果你的服务器端代码无法验证其接收到的数据,则当格式不正确的数据(或数据太大、类型错误等)输入数据库时,可能会发生灾难。

¥Warning: HTML form validation is not a substitute for scripts that ensure that the entered data is in the proper format.It's far too easy for someone to make adjustments to the HTML that allow them to bypass the validation, or to remove it completely. It's also possible for someone to bypass your HTML entirely and submit the data directly to your server. If your server-side code fails to validate the data it receives, disaster could strike when improperly-formatted data (or data which is too large, is of the wrong type, and so forth) is entered into your database.

基本验证

¥Basic validation

浏览器自动提供验证,以确保只有与 Internet 电子邮件地址标准格式匹配的文本才会输入到输入框中。浏览器使用相当于以下正则表达式的算法:

¥Browsers automatically provide validation to ensure that only text that matches the standard format for Internet email addresses is entered into the input box. Browsers use an algorithm equivalent to the following regular expression:

js
/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;

要了解有关表单验证如何工作以及如何利用 :valid:invalid CSS 属性根据当前值是否有效设置输入样式的更多信息,请参阅 表单数据验证

¥To learn more about how form validation works and how to take advantage of the :valid and :invalid CSS properties to style the input based on whether the current value is valid, see Form data validation.

注意:存在与国际域名和 HTML 中电子邮件地址验证相关的已知规范问题。详情请参见 W3C 错误 15489

¥Note: There are known specification issues related to international domain names and the validation of email addresses in HTML. See W3C bug 15489 for details.

模式验证

¥Pattern validation

如果你需要对输入的电子邮件地址进行进一步限制,而不仅仅是 "任何看起来像电子邮件地址的字符串,",则可以使用 pattern 属性来指定 regular expression,该值必须匹配才能有效。如果指定了 multiple 属性,则逗号分隔的值列表中的每个单独项目都必须与 regular expression 匹配。

¥If you need the entered email address to be restricted further than just "any string that looks like an email address," you can use the pattern attribute to specify a regular expression the value must match for it to be valid. If the multiple attribute is specified, each individual item in the comma-delineated list of values must match the regular expression.

例如,假设你正在为 Best Startup Ever, Inc. 的员工构建一个页面。这将使他们可以联系 IT 部门寻求帮助。在我们的简化表单中,用户需要输入他们的电子邮件地址和一条描述他们需要帮助的问题的消息。我们希望确保用户不仅提供有效的电子邮件地址,而且出于安全目的,我们要求该地址是内部公司电子邮件地址。

¥For example, let's say you're building a page for employees of Best Startup Ever, Inc. which will let them contact their IT department for help. In our simplified form, the user needs to enter their email address and a message describing the problem they need help with. We want to ensure that not only does the user provide a valid email address, but for security purposes, we require that the address be an internal corporate email address.

由于 email 类型的输入会根据标准电子邮件地址验证和指定的 pattern 进行验证,因此你可以轻松实现这一点。让我们看看如何:

¥Since inputs of type email validate against both the standard email address validation and the specified pattern, you can implement this easily. Let's see how:

css
body {
  font: 16px sans-serif;
}

.emailBox {
  padding-bottom: 20px;
}

.messageBox {
  padding-bottom: 20px;
}

label {
  line-height: 22px;
}

label::after {
  content: ":";
}
html
<form>
  <div class="emailBox">
    <label for="emailAddress">Your email address</label><br />
    <input
      id="emailAddress"
      type="email"
      size="64"
      maxlength="64"
      required
      placeholder="username@beststartupever.com"
      pattern=".+@beststartupever\.com"
      title="Please provide only a Best Startup Ever corporate email address" />
  </div>

  <div class="messageBox">
    <label for="message">Request</label><br />
    <textarea
      id="message"
      cols="80"
      rows="8"
      required
      placeholder="My shoes are too tight, and I have forgotten how to dance."></textarea>
  </div>
  <input type="submit" value="Send Request" />
</form>

我们的 <form> 包含一个 email 类型的 <input>(用于用户的电子邮件地址)、一个 <textarea>(用于为 IT 输入消息)和一个 "submit" 类型的 <input>(创建一个用于提交表单的按钮)。每个文本输入框都有一个与之关联的 <label>,让用户知道对他们的期望。

¥Our <form> contains one <input> of type email for the user's email address, a <textarea> to enter their message for IT into, and an <input> of type "submit", which creates a button to submit the form. Each text entry box has a <label> associated with it to let the user know what's expected of them.

让我们仔细看看电子邮件地址输入框。其 sizemaxlength 属性均设置为 64,以便显示可容纳 64 个字符的电子邮件地址的空间,并将实际输入的字符数限制为最多 64 个。指定了 required 属性,因此必须提供有效的电子邮件地址。

¥Let's take a closer look at the email address entry box. Its size and maxlength attributes are both set to 64 in order to show room for 64 characters worth of email address, and to limit the number of characters actually entered to a maximum of 64. The required attribute is specified, making it mandatory that a valid email address be provided.

提供了适当的 placeholderusername@beststartupever.com)来证明有效条目的构成。该字符串表明应输入电子邮件地址,并表明它应该是公司 beststartupever.com 账户。除此之外,使用类型 email 将验证文本以确保其格式类似于电子邮件地址。如果输入框中的文本不是电子邮件地址,你将收到如下所示的错误消息:

¥An appropriate placeholder is provided—username@beststartupever.com—to demonstrate what constitutes a valid entry. This string demonstrates both that an email address should be entered, and suggests that it should be a corporate beststartupever.com account. This is in addition to the fact that using type email will validate the text to ensure that it's formatted like an email address. If the text in the input box isn't an email address, you'll get an error message that looks something like this:

Invalid email address in error state with a popout from the input reading 'please enter an email address'.

如果我们就此置之不理,我们至少会验证合法的电子邮件地址。但我们想更进一步:我们要确保电子邮件地址实际上采用“username@beststartupever.com”形式。这是我们将使用 pattern 的地方。我们将 pattern 设置为 .+@beststartupever.com。这个简单的正则表达式请求一个字符串,该字符串至少包含一个任意类型的字符,然后是 "@",后跟域名 "beststartupever.com"。

¥If we left things at that, we would at least be validating on legitimate email addresses. But we want to go one step farther: we want to make sure that the email address is in fact in the form "username@beststartupever.com". This is where we'll use pattern. We set pattern to .+@beststartupever.com. This simple regular expression requests a string that consists of at least one character of any kind, then an "@" followed by the domain name "beststartupever.com".

请注意,这甚至还不足以过滤有效的电子邮件地址;它将允许诸如 "@beststartupever.com"(注意前导空格)或 "@@beststartupever.com" 之类的内容,但这两者都无效。但是,浏览器会针对指定文本运行标准电子邮件地址过滤器和我们的自定义模式。结果,我们最终得到了 "确保这类似于有效的电子邮件地址,如果是,请确保它也是 beststartupever.com 地址。" 的验证

¥Note that this is not even close to an adequate filter for valid email addresses; it would allow things such as " @beststartupever.com" (note the leading space) or "@@beststartupever.com", neither of which is valid. However, the browser runs both the standard email address filter and our custom pattern against the specified text. As a result, we wind up with a validation which says "make sure this resembles a valid email address, and if it is, make sure it's also a beststartupever.com address."

建议将 title 属性与 pattern 一起使用。如果这样做,title 必须描述该模式。也就是说,它应该解释数据应该采用什么格式,而不是任何其他信息。这是因为 title 可能会作为验证错误消息的一部分显示或读出。例如,浏览器可能会显示消息 "输入的文本与所需的模式不匹配。",后跟你指定的 title。如果你的 title 类似于 "电子邮件地址",则结果将是消息“输入的文本与所需的模式不匹配。电子邮件地址”,这不太好。

¥It's advisable to use the title attribute along with pattern. If you do, the title must describe the pattern. That is, it should explain what format the data should take on, rather than any other information. That's because the title may be displayed or spoken as part of a validation error message. For example, the browser might present the message "The entered text doesn't match the required pattern." followed by your specified title. If your title is something like "Email address", the result would be the message "The entered text doesn't match the required pattern. Email address", which isn't very good.

这就是为什么我们指定字符串 "请仅提供最佳初创企业电子邮件地址" 通过这样做,生成的完整错误消息可能类似于“输入的文本与所需的模式不匹配。请仅提供有史以来最佳初创公司的公司电子邮件地址。”

¥That's why, instead, we specify the string "Please provide only a Best Startup Ever corporate email address" By doing that, the resulting full error message might be something like "The entered text doesn't match the required pattern. Please provide only a Best Startup Ever corporate email address."

A valid email address, but the input is in error state with a popout from the input reading 'The entered text doesn't match the required pattern. Please provide only a Best Startup Ever corporate email address.'

注意:如果你在编写验证正则表达式时遇到麻烦并且它们无法正常工作,请检查浏览器的控制台;那里可能有有用的错误消息来帮助你解决问题。

¥Note: If you run into trouble while writing your validation regular expressions and they're not working properly, check your browser's console; there may be helpful error messages there to aid you in solving the problem.

示例

¥Examples

这里我们有一个 ID 为 emailAddress 的电子邮件输入,最大长度为 256 个字符。输入框本身的物理宽度为 64 个字符,只要字段为空,就会显示文本 user@example.gov 作为占位符。此外,通过使用 multiple 属性,该框被配置为允许用户输入零个或多个以逗号分隔的电子邮件地址,如 允许多个电子邮件地址 中所述。最后,list 属性包含 <datalist> 的 ID,<datalist><option> 指定用户可以从中选择的一组建议值。

¥Here we have an email input with the ID emailAddress which is allowed to be up to a maximum of 256 characters long. The input box itself is physically 64 characters wide, and displays the text user@example.gov as a placeholder anytime the field is empty. In addition, by using the multiple attribute, the box is configured to allow the user to enter zero or more email addresses, separated by commas, as described in Allowing multiple email addresses. As a final touch, the list attribute contains the ID of a <datalist> whose <option>s specify a set of suggested values the user can choose from.

作为补充,<label> 元素用于为电子邮件输入框建立标签,其 for 属性引用 <input> 元素的 emailAddress ID。通过以这种方式关联两个元素,单击标签将聚焦输入元素。

¥As an added touch, the <label> element is used to establish a label for the email entry box, with its for attribute referencing the emailAddress ID of the <input> element. By associating the two elements in this way, clicking on the label will focus the input element.

html
<label for="emailAddress">Email</label><br />
<input
  id="emailAddress"
  type="email"
  placeholder="user@example.gov"
  list="defaultEmails"
  size="64"
  maxlength="256"
  multiple />

<datalist id="defaultEmails">
  <option value="jbond007@mi6.defence.gov.uk"></option>
  <option value="jbourne@unknown.net"></option>
  <option value="nfury@shield.org"></option>
  <option value="tony@starkindustries.com"></option>
  <option value="hulk@grrrrrrrr.arg"></option>
</datalist>

技术总结

¥Technical summary

代表电子邮件地址的字符串,或为空
活动 changeinput
支持的通用属性 autocompletelistmaxlengthminlengthmultiplenamepatternplaceholderreadonlyrequiredsizetype
IDL 属性 listvalue
DOM 接口

HTMLInputElement

方法 select()
隐式 ARIA 角色 list 属性: textbox
list 属性: combobox

规范

Specification
HTML Standard
# email-state-(type=email)

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看