HTML5表单验证不适用于pattern =“ \ d {10}”

时间:2018-11-20 01:11:02

标签: html5 validation

我有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位?

2 个答案:

答案 0 :(得分:2)

问题在于pattern attribute仅适用于the following input types

  • 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>

答案 1 :(得分:1)

您可以使用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>

相关问题