HTML 属性:pattern

pattern 属性指定表单控件的值应匹配的 正则表达式。如果非 null 值不符合 pattern 值设置的约束,则 ValidityState 对象的只读 patternMismatch 属性将为 true。

¥The pattern attribute specifies a regular expression the form control's value should match. If a non-null value doesn't conform to the constraints set by the pattern value, the ValidityState object's read-only patternMismatch property will be true.

Try it

概述

¥Overview

pattern 属性是 texttelemailurlpasswordsearch 输入类型的属性。

¥The pattern attribute is an attribute of the text, tel, email, url, password, and search input types.

指定时,pattern 属性是一个正则表达式,输入的 value 必须与该正则表达式匹配才能传递 约束验证 的值。它必须是有效的 JavaScript 正则表达式,如 RegExp 类型所使用的以及我们的 正则表达式指南 中所记录的那样。

¥The pattern attribute, when specified, is a regular expression which 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.

该模式的正则表达式使用 'v' 进行编译。这使得正则表达式 unicode-aware 成为可能,并且还改变了字符类的解释方式。这允许字符类集交集和减法运算,并且除了 ]\ 之外,如果以下字符表示文字字符,则必须使用 \ 反斜杠进行转义:(, ), [, {, }, /, -, |.2023 年中期之前,指定了 'u' 标志;如果你要更新旧代码,本文档概述了差异

¥The pattern's regular expression is compiled with the 'v' flag. This makes the regular expression unicode-aware, and also changes how character classes are interpreted. This allows character class set intersection and subtraction operations, and in addition to ] and \, the following characters must be escaped using a \ backslash if they represent literal characters: (, ), [, {, }, /, -, |. Before mid-2023, the 'u' flag was specified instead; If you're updating older code, this document outlines the differences.

模式的正则表达式必须匹配整个输入的 value,而不是匹配子字符串 - 就好像 ^(?: 隐含在模式的开头,)$ 隐含在模式的结尾。

¥The pattern's regular expression must match the entire input's value, rather than matching a substring - as if a ^(?: were implied at the start of the pattern and )$ at the end.

模式文本周围不应指定正斜杠。如果属性值不存在、为空字符串或无效,则不应用正则表达式。

¥No forward slashes should be specified around the pattern text. No regular expression is applied if the attribute value is absent, an empty string, or invalid.

一些支持模式属性的输入类型,特别是 emailurl 输入类型,具有必须匹配的预期值语法。如果模式属性不存在,并且值与该值类型的预期语法不匹配,则 ValidityState 对象的只读 typeMismatch 属性将为 true。

¥Some of the input types supporting the pattern attribute, notably the email and url input types, have expected value syntaxes that must be matched. If the pattern attribute isn't present, and the value doesn't match the expected syntax for that value type, the ValidityState object's read-only typeMismatch property will be true.

约束验证

¥Constraint validation

如果输入的值不是空字符串并且该值与整个正则表达式不匹配,则 ValidityState 对象的 patternMismatch 属性为 true,报告存在约束冲突。

¥If the input's value is not the empty string and the value does not match the entire regular expression, there is a constraint violation reported by the ValidityState object's patternMismatch property being true.

注意:如果未指定 pattern 属性值,则其值隐式为空字符串。因此,任何非空输入 value 将导致违反约束。

¥Note: If the pattern attribute is specified with no value, its value is implicitly the empty string. Thus, any non-empty input value will result in constraint violation.

可用性和可访问性考虑因素

¥Usability and accessibility considerations

当包含 pattern 时,请在控件附近的可见文本中提供模式的描述。此外,还包括提供模式描述的 title 属性。用户代理可以在约束验证期间使用标题内容来告诉用户模式不匹配。某些浏览器会显示带有标题内容的工具提示,从而提高视力正常的用户的可用性。此外,当控件获得焦点时,辅助技术可以大声朗读标题,但这不应依赖于可访问性。

¥When including a pattern, provide a description of the pattern in visible text near the control. Additionally, include a title attribute which gives a description of the pattern. User agents may use the title contents during constraint validation to tell the user that the pattern is not matched. Some browsers show a tooltip with title contents, improving usability for sighted users. Additionally, assistive technology may read the title aloud when the control gains focus, but this should not be relied upon for accessibility.

不鼓励仅依赖 title 属性来可视化显示文本内容,因为许多用户代理不以可访问的方式公开该属性。尽管某些浏览器会在悬停带有标题的元素时显示工具提示,但这会忽略仅使用键盘和仅触摸的用户。这是你必须包含通知用户如何填写控件以满足要求的信息的几个原因之一。

¥Only relying on the title attribute for the visual display of text content is discouraged, as many user agents do not expose the attribute in an accessible manner. Although some browsers show a tooltip when an element with a title is hovered, that leaves out keyboard-only and touch-only users. This is one of the several reasons you must include information informing users how to fill out the control to match the requirements.

虽然某些浏览器使用 title 来填充错误消息,但由于浏览器有时也会在悬停时将标题显示为文本,因此它会在非错误情况下显示,因此请注意不要将标题视为发生了错误。

¥While titles are used by some browsers to populate error messaging, because browsers sometimes also show the title as text on hover, it therefore shows in non-error situations, so be careful not to word titles as if an error has occurred.

示例

¥Examples

匹配调用号码

¥Matching a phone number

鉴于以下情况:

¥Given the following:

html
<p>
  <label>
    Enter your phone number in the format (123) - 456 - 7890 (<input
      name="tel1"
      type="tel"
      pattern="[0-9]{3}"
      placeholder="###"
      aria-label="3-digit area code"
      size="2" />) -
    <input
      name="tel2"
      type="tel"
      pattern="[0-9]{3}"
      placeholder="###"
      aria-label="3-digit prefix"
      size="2" />
    -
    <input
      name="tel3"
      type="tel"
      pattern="[0-9]{4}"
      placeholder="####"
      aria-label="4-digit number"
      size="3" />
  </label>
</p>

这里,我们有一个北美调用号码的 3 个部分,其中隐式标签包含调用号码的所有三个组成部分,分别期望 3 位数字、3 位数字和 4 位数字,如每个部分上设置的 pattern 属性所定义。

¥Here we have 3 sections for a north American phone number with an implicit label encompassing all three components of the phone number, expecting 3-digits, 3-digits and 4-digits respectively, as defined by the pattern attribute set on each.

如果值太长或太短,或者包含非数字字符,则 patternMismatch 将为 true。当 true 时,元素与 :invalid CSS 伪类匹配。

¥If the values are too long or too short, or contain characters that aren't digits, the patternMismatch will be true. When true, the element matches the :invalid CSS pseudo-classes.

css
input:invalid {
  border: red solid 3px;
}

如果我们使用 minlengthmaxlength 属性,我们可能会看到 validityState.tooLongvalidityState.tooShort 为 true。

¥If we had used minlength and maxlength attributes instead, we may have seen validityState.tooLong or validityState.tooShort being true.

指定模式

¥Specifying a pattern

你可以使用 pattern 属性指定输入值必须匹配的正则表达式才能被视为有效(有关使用正则表达式验证输入的简单速成课程,请参阅 根据正则表达式进行验证)。

¥You can use the pattern attribute to specify a regular expression that the inputted value must match in order to be considered valid (see Validating against a regular expression for a simple crash course on using regular expressions to validate inputs).

下面的示例将值限制为 4-8 个字符,并要求它仅包含小写字母。

¥The example below restricts the value to 4-8 characters and requires that it contain only lower-case letters.

html
<form>
  <div>
    <label for="uname">Choose a username: </label>
    <input
      type="text"
      id="uname"
      name="name"
      required
      size="45"
      pattern="[a-z]{4,8}"
      title="4 to 8 lowercase letters" />
    <span class="validity"></span>
    <p>Usernames must be lowercase and 4-8 characters in length.</p>
  </div>
  <div>
    <button>Submit</button>
  </div>
</form>
css
div {
  margin-bottom: 10px;
  position: relative;
}

p {
  font-size: 80%;
  color: #999;
}

input + span {
  padding-right: 30px;
}

input:invalid + span::after {
  position: absolute;
  content: "✖";
  padding-left: 5px;
}

input:valid + span::after {
  position: absolute;
  content: "✓";
  padding-left: 5px;
}

呈现如下:

¥This renders like so:

规范

Specification
HTML Standard
# attr-input-pattern

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看