在我的表单中,我想使用新的HTML表单类型,例如<input type="url" />(关于类型的更多信息在这里)。

问题是Chrome想要超级有用,并验证这些元素为我,除了它在这方面很糟糕。如果它没有通过内置验证,除了元素获得焦点之外,没有其他消息或指示。我用“http://”预填充URL元素,所以我自己的自定义验证只是将这些值视为空字符串,但Chrome拒绝了这一点。如果我能改变它的验证规则,那也可以。

我知道我可以回到使用type="text",但我想使用这些新类型提供的很好的增强(例如:它自动切换到移动设备上的自定义键盘布局):

有没有办法关闭或自定义自动验证?


当前回答

如果您想在HTML中禁用表单的客户端验证,请向表单元素添加novalidate属性。例:

<form method="post" action="/foo" novalidate>...</form>

看到https://www.w3.org/TR/html5/sec-forms.html element-attrdef-form-novalidate

其他回答

我找到了一个解决方案,Chrome与CSS这个下面的选择器没有绕过本机验证形式,这可能是非常有用的。

form input::-webkit-validation-bubble-message, 
form select::-webkit-validation-bubble-message,
form textarea::-webkit-validation-bubble-message {
    display:none;
} 

通过这种方式,你还可以自定义你的消息…

我在这一页上找到了解决方案: http://trac.webkit.org/wiki/Styling%20Form%20Controls

我只是想添加,在你的表单中使用novalidate属性只会阻止浏览器发送表单。浏览器仍然计算数据并添加:valid和:invalid伪类。

我发现这一点是因为有效和无效的伪类是我一直在使用的HTML5样板样式表的一部分。我只是删除了CSS文件中与伪类相关的条目。如果有人找到了其他解决方案,请告诉我。

您可以添加一些javascript来抑制那些令人讨厌的验证气泡,并添加您自己的验证器。

document.addEventListener('invalid', (function(){
    return function(e) {
      //prevent the browser from showing default error bubble / hint
      e.preventDefault();
      // optionally fire off some custom validation handler
      // myValidation();
    };
})(), true);

最好的解决方案是使用文本输入,并添加属性inputmode="url"来提供url键盘功能。HTML5规范就是为了这个目的而设计的。如果你保持type="url",你会得到语法验证,这在任何情况下都不是有用的(最好检查它是否返回404错误,而不是语法相当宽松,没有很大的帮助)。

您还可以使用属性pattern="https?://来覆盖默认模式。例如“+”就显得更宽容。

将novalidate属性放在表单中并不是对所问问题的正确答案,因为它删除了表单中所有字段的验证,例如,您可能希望保留对电子邮件字段的验证。

使用jQuery禁用验证也是一个糟糕的解决方案,因为它完全可以在没有JavaScript的情况下工作。

In my case, I put a select element with 2 options (http:// or https://) before the URL input because I just need websites (and no ftp:// or other things). This way I avoid typing this weird prefix (the biggest regret of Tim Berners-Lee and maybe the main source of URL syntax errors) and I use a simple text input with inputmode="url" with placeholders (without HTTP). I use jQuery and server side script to validate the real existence of the web site (no 404) and to remove the HTTP prefix if inserted (I avoid to use a pattern like pattern="^((?http).)*$" to prevent putting the prefix because I think it is better to be more permissive)

如果您想在HTML中禁用表单的客户端验证,请向表单元素添加novalidate属性。例:

<form method="post" action="/foo" novalidate>...</form>

看到https://www.w3.org/TR/html5/sec-forms.html element-attrdef-form-novalidate