HTML5 表单验证不适用于模式 = "d{10}"



我有HTML:

#container {
width: 600px;
max-width: 100%;
margin: 1em auto;
}
<div id="container">
<form>
<input type="text" id="text" placeholder="enter some text" required maxlength="10" pattern="^[a-z,A-Z]{1,10}$"><br />
<input type="number" id="number" placeholder="enter a number" required maxlength="10" pattern="d{10}"><br />
<input type="submit">
</form>
</div>

当我在第二个字段中输入一个超过10位的数字,然后单击提交时,只要我在第一个字段中有1-10个字母,表单就会提交。

我认为pattern="d{10}"确保字段的数字不超过10?

问题是pattern属性仅适用于以下input类型:

  • date
  • email
  • password
  • search
  • tel
  • text
  • url

因为它不适用于number,所以不会触发验证。

为了解决这个问题,我建议使用type="text",因为您的模式已经明确要求数字输入:

<!doctype html>
<html>
<head>
<style>
#container {width: 600px; max-width: 100%; margin: 1em auto;}
</style>
</head>
<body>
<div id="container">
<form>
<input type="text" id="text" placeholder="enter some text" required maxlength="10" pattern="^[a-z,A-Z]{1,10}$"><br />
<input type="text" id="number" placeholder="enter a number" required maxlength="10" pattern="^d{10}$"><br />
<input type="submit">
</form>
</div>
</body>
</html>

您可以使用max="9999999999":

#container {
width: 600px;
max-width: 100%;
margin: 1em auto;
}
<div id="container">
<form>
<input type="text" id="text" placeholder="enter some text" required maxlength="10" pattern="^[a-z,A-Z]{1,10}$"><br />
<input type="number" id="number" placeholder="enter a number" required max="9999999999"><br />
<input type="submit">
</form>
</div>

最新更新