HTML pattern 属性

htmlweb developmentfront end technology更新于 2025/12/21 6:04:17

HTML pattern 属性定义一个正则表达式,用于匹配 HTML 文档中 <input> HTML 元素的值。

语法

以下是语法 −

<input pattern=”regular expression”>

让我们看一个 HTML pattern 属性的示例 −

示例

<!DOCTYPE html>
<html>
<style>
   body {
      color: #000;
      height: 100vh;
      background: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%) no-repeat;
      text-align: center;
   }
   input[type='password'] {
      width: 300px;
      padding: 8px 16px;
      border: 2px solid #fff;
      background: transparent;
      border-radius: 20px;
      display: block;
      margin: 1rem auto;
      outline: none;
   }
   .btn {
      background: #db133a;
      border: none;
      height: 2rem;
      border-radius: 20px;
      width: 330px;
      display: block;
      color: #fff;
      outline: none;
      cursor: pointer;
      margin: 1rem auto;
   }
   ::placeholder {
      color: #000;
   }
</style>
<body>
<h1>HTML pattern attribute Example</h1>
<form action="">
<input type="password" placeholder="Enter your account password" required pattern=".{8,}">
<input type="submit" value="Submit" class="btn" onclick='check()'>
</form>
<div class="show"></div>
<script>
   function check() {
      if (document.querySelector("input[type='password']").value.length < 8) {
         document.querySelector(".show").innerHTML = 'Please enter a password of more than or equal             to 8 characters.'
      };
   }
</script>
</body>
</html>

输出

输入少于 8 个字符的密码,然后点击"提交"按钮以显示警告消息。


相关文章


有用资源