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

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

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

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


当前回答

在JSX (JavaScript, React, Angular, Vue等)中,你需要在表单中添加noValidate(驼峰大写V是必要的):

<form onSubmit={handleSubmit(data)} noValidate>

正如Jakob S所说,在纯HTML的情况下,添加novalidate到表单元素:

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

其他回答

下面是我用来防止chrome和opera显示无效输入对话框的函数,即使使用novalidate。

window.submittingForm = false;
$('input[novalidate]').bind('invalid', function(e) {
    if(!window.submittingForm){
        window.submittingForm = true;
        $(e.target.form).submit();
        setTimeout(function(){window.submittingForm = false;}, 100);
    }
    e.preventDefault();
    return false;
});

如果你将一个表单元素标记为required=""那么novalidate=""没有帮助。

绕过必需的验证的一种方法是禁用元素。

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

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

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

最好的解决方案是使用文本输入,并添加属性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)

我找到了一个解决方案,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