我目前有一个电话号码的输入元素,并试图使用模式属性,但它拒绝这样做。它说“验证(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属性,它现在正在工作!但我唯一的问题是,当我点击提交时,即使格式不匹配,也会提交表单。
<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
属性仅允许用于以下类型:email
,password
,search
,tel
,text
或url
。您的正则表达式([\+]\d{3}d{9}
)也无效。您可以尝试以下规则之一:
[\+]\d{3}\d{9}
[\+]\d{12}
你在第二个\
之前缺少d
以匹配数字。第二种模式是第一种模式的缩小版本。
它已修复,只是在我的javascript中添加了这个。
/[+]\的{3}的{9}/.test(phone no)
您可以向标记添加oninvalid属性
<input type="text" name="HasAPattern" pattern="\w{3}" title="Enter 3 characters" oninvalid="setCustomValidity('Needs to match patern')" >
HTMLSelectElement.setCustomValidity()方法将selection元素的自定义有效性消息设置为指定的消息。使用空字符串表示该元素没有自定义有效性错误。
你也可以使用像event.preventDefault();
这样的代码取消提交,如果无效的话