Html 禁用 HTML5 表单元素的验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3090369/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 03:33:26  来源:igfitidea点击:

Disable validation of HTML5 form elements

validationformshtmlinput

提问by nickf

In my forms, I'd like to use the new HTML5 form types, for example <input type="url" />(more info about the types here).

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

The problem is that Chrome wants to be super helpful and validate these elements for me, except that it sucks at it. If it fails the built-in validation, there's no message or indication other than the element getting focus. I prefill URL elements with "http://", and so my own custom validation just treats those values as empty strings, however Chrome rejects that. If I could change its validation rules, that would work too.

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

I know I could just revert back to using type="text"but I want the nice enhancements using these new types offers (eg: it automatically switches to a custom keyboard layout on mobile devices):

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

So, is there a way to switch off or customise the automatic validation?

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

回答by Jakob S

If you want to disable client side validation for a form in HTML5 add a novalidate attribute to the form element. Ex:

如果要禁用 HTML5 中表单的客户端验证,请向表单元素添加 novalidate 属性。前任:

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

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

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

回答by Ben Boyle

I had a read of the spec and did some testing in Chrome, and if you catch the "invalid" event and return false that seems to allow form submission.

我阅读了规范并在 Chrome 中进行了一些测试,如果您捕获“无效”事件并返回似乎允许表单提交的 false。

I am using jquery, with this HTML.

我正在使用 jquery 和这个 HTML。

// suppress "invalid" events on URL inputs
$('input[type="url"]').bind('invalid', function() {
  alert('invalid');
  return false;
});

document.forms[0].onsubmit = function () {
  alert('form submitted');
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input type="url" value="http://" />
  <button type="submit">Submit</button>
</form>

I haven't tested this in any other browsers.

我没有在任何其他浏览器中测试过这个。

回答by BFTrick

I just wanted to add that using the novalidate attribute in your form will only prevent the browser from sending the form. The browser still evaluates the data and adds the :valid and :invalid pseudo classes.

我只是想补充一点,在表单中使用 novalidate 属性只会阻止浏览器发送表单。浏览器仍然评估数据并添加 :valid 和 :invalid 伪类。

I found this out because the valid and invalid pseudo classes are part of the HTML5 boilerplate stylesheet which I have been using. I just removed the entries in the CSS file that related to the pseudo classes. If anyone finds another solution please let me know.

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

回答by plancton

The best solution is to use a text input and add the attribute inputmode="url" to provide the URL keyboard facilities. The HTML5 specification was thought for this purpose. If you keep type="url" you get the syntax validation which is not useful in every case (it is better to check if it returns a 404 error instead of the syntax which is quite permissive and is not of a great help).

最好的解决方案是使用文本输入并添加属性 inputmode="url" 以提供 URL 键盘功能。HTML5 规范就是为此目的而考虑的。如果你保持 type="url" 你得到的语法验证不是在所有情况下都有用(最好检查它是否返回 404 错误,而不是非常宽松且没有很大帮助的语法)。

You also have the possibility to override the default pattern with the attribute pattern="https?://.+" for example to be more permissive.

您还可以使用属性 pattern="https?://.+" 覆盖默认模式,例如更宽容。

Putting the novalidate attribute to the form is not the right answer to the asked question because it removes validation for all the fields in the form and you may want to keep validation for email fields for example.

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

Using jQuery to disable validation is also a bad solution because it should absolutely work without JavaScript.

使用 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)

就我而言,我在 URL 输入之前放置了一个带有 2 个选项(http:// 或 https://)的 select 元素,因为我只需要网站(而不需要 ftp:// 或其他东西)。这样我就避免输入这个奇怪的前缀(Tim Berners-Lee 的最大遗憾,也许是 URL 语法错误的主要来源),我使用带有 inputmode="url" 的简单文本输入和占位符(没有 HTTP)。我使用 jQuery 和服务器端脚本来验证网站的真实存在(没有 404)并在插入时删除 HTTP 前缀(我避免使用像 pattern="^((?http).)*$" 这样的模式防止放置前缀,因为我认为最好更宽容)

回答by John Kugelman

Instead of trying to do an end run around the browser's validation, you could put the http://in as placeholder text. This is from the very page you linked:

您可以将http://in 作为占位符文本放入,而不是尝试围绕浏览器的验证进行结束运行。这是来自您链接的页面:

Placeholder Text

The first improvement HTML5 brings to web forms is the ability to set placeholder text in an input field. Placeholder text is displayed inside the input field as long as the field is empty and not focused. As soon as you click on (or tab to) the input field, the placeholder text disappears.

You've probably seen placeholder text before. For example, Mozilla Firefox 3.5 now includes placeholder text in the location bar that reads “Search Bookmarks and History”:

enter image description here

When you click on (or tab to) the location bar, the placeholder text disappears:

enter image description here

Ironically, Firefox 3.5 does not support adding placeholder text to your own web forms. C'est la vie.

Placeholder Support

IE  FIREFOX SAFARI  CHROME  OPERA   IPHONE  ANDROID
·   3.7+    4.0+    4.0+    ·       ·       ·

Here's how you can include placeholder text in your own web forms:

<form>
  <input name="q" placeholder="Search Bookmarks and History">
  <input type="submit" value="Search">
</form>

Browsers that don't support the placeholderattribute will simply ignore it. No harm, no foul. See whether your browser supports placeholder text.

占位符文本

HTML5 为 Web 表单带来的第一个改进是能够在输入字段中设置占位符文本。只要输入字段为空且未聚焦,占位符文本就会显示在输入字段内。只要您单击(或使用 Tab 键)输入字段,占位符文本就会消失。

您之前可能已经看过占位符文本。例如,Mozilla Firefox 3.5 现在在位置栏中包含占位符文本,内容为“搜索书签和历史记录”:

在此处输入图片说明

当您单击(或选项卡)位置栏时,占位符文本消失:

在此处输入图片说明

具有讽刺意味的是,Firefox 3.5 不支持向您自己的 Web 表单添加占位符文本。这就是生活。

占位符支持

IE  FIREFOX SAFARI  CHROME  OPERA   IPHONE  ANDROID
·   3.7+    4.0+    4.0+    ·       ·       ·

以下是在自己的 Web 表单中包含占位符文本的方法:

<form>
  <input name="q" placeholder="Search Bookmarks and History">
  <input type="submit" value="Search">
</form>

不支持该placeholder属性的浏览器将简单地忽略它。没有伤害,没有犯规。查看您的浏览器是否支持占位符文本

It wouldn't be exactly the same since it wouldn't provide that "starting point" for the user, but it's halfway there at least.

它不会完全相同,因为它不会为用户提供“起点”,但至少它已经完成了一半。

回答by Val Entin

I found a solution for Chrome with CSS this following selector without bypassing the native verification form which could be very useful.

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

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

By this way, you can also customise your message...

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

I got the solution on this page : http://trac.webkit.org/wiki/Styling%20Form%20Controls

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

回答by brainSquezer

Just use novalidatein your form.

只需在您的表单中使用novalidate 即可

<form name="myForm" role="form" novalidate class="form-horizontal" ng-hide="formMain">

Cheers!!!

干杯!!!

回答by Tobias Kolb

you can add some javascript to surpress those obnoxious validation bubbles and add your own validators.

您可以添加一些 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);

回答by cweiske

If you mark a form element as required=""then novalidate=""does not help.

如果您将表单元素标记为required=""thennovalidate=""则无济于事。

A way to circumvent the requiredvalidation is to disable the element.

绕过required验证的一种方法是禁用元素

回答by Tony Brix

Here is the function I use to prevent chrome and opera from showing the invalid input dialog even when using novalidate.

这是我用来防止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;
});