HTML5 - Pattern属性不能在input元素中使用

问题描述 投票:3回答:3

我目前有一个电话号码的输入元素,并试图使用模式属性,但它拒绝这样做。它说“验证(HTML5):模式不是元素输入的有效属性”!当我将类型更改为“text”时,它表示pattern属性仅在标题存在时才有效!

<input type="number" class="form-control"data-require="" id="Mobile" placeholder="Mobile No" autocomplete="off" pattern="[\+]\d{3}d{9}" required>

更新:

我添加了title属性,它现在正在工作!但我唯一的问题是,当我点击提交时,即使格式不匹配,也会提交表单。

html html5 forms validation input
3个回答
5
投票

<input>应该在没有title属性的情况下有效(在https://validator.nu/上验证):

<!DOCTYPE html>
<html>
  <head>
    <title>Test</title>
  </head>
  <body>
    <input type="text" class="form-control" data-require="" id="Mobile" placeholder="Mobile No" autocomplete="off" pattern="[\+]\d{3}d{9}" required>
  </body>
</html>

其他变化:

  • 在属性data-require之前缺少空格。
  • pattern属性仅允许用于以下类型:emailpasswordsearchteltexturl

您的正则表达式([\+]\d{3}d{9})也无效。您可以尝试以下规则之一:

  • [\+]\d{3}\d{9}
  • [\+]\d{12}

你在第二个\之前缺少d以匹配数字。第二种模式是第一种模式的缩小版本。


0
投票

它已修复,只是在我的javascript中添加了这个。

/[+]\的{3}的{9}/.test(phone no)


-1
投票

您可以向标记添加oninvalid属性

<input type="text" name="HasAPattern" pattern="\w{3}" title="Enter 3 characters" oninvalid="setCustomValidity('Needs to match patern')" >

HTMLSelectElement.setCustomValidity()方法将selection元素的自定义有效性消息设置为指定的消息。使用空字符串表示该元素没有自定义有效性错误。

你也可以使用像event.preventDefault();这样的代码取消提交,如果无效的话

© www.soinside.com 2019 - 2024. All rights reserved.