检查浏览器是否内置HTML5表单验证?

Ian*_* Y. 22 validation html5

如何检查浏览器是否具有内置的HTML5表单验证功能?通过这样做,我们不需要在可以自己验证表单的浏览器上应用jQuery表单验证功能.

[解决]根据ThinkingStiff的回答,这是一种方式:

if (typeof document.createElement("input").checkValidity == "function") {
    alert("Your browser has built-in form validation!");
}
Run Code Online (Sandbox Code Playgroud)

Thi*_*iff 26

只需检查checkValidity()函数是否存在:

演示:http://jsfiddle.net/ThinkingStiff/cmSJw/

function hasFormValidation() {

    return (typeof document.createElement( 'input' ).checkValidity == 'function');

};
Run Code Online (Sandbox Code Playgroud)

像这样称呼它:

if( hasFormValidation() ) {
    //HTML5 Form Validation supported
};
Run Code Online (Sandbox Code Playgroud)

  • Safari和几个移动webkit浏览器(包括3.0之前版本中的默认Android浏览器)具有checkValidity方法的实现.但是,当表单无效时,浏览器绝不会向用户提供任何反馈,并允许提交表单.如果浏览器支持约束验证api,这使得checkValidity方法不可靠. (23认同)
  • `HTMLFormElement.prototype.checkValidity` 不是一种更简洁的检查存在的方法吗? (2认同)

小智 7

你可以使用Modernizr javascript http://www.modernizr.com/来做到这一点.你可以从这篇文章html5表格验证modernizr safari获得帮助.您还可以利用modernizr负载

Modernizr.load()的基本语法是将具有以下属性的对象传递给它:

  • test:要检测的Modernizr属性.
  • 是的:如果测试成功,您要加载的脚本的位置.将数组用于多个脚本.
  • nope:如果测试失败,您要加载的脚本的位置.将数组用于多个脚本.
  • complete:加载外部脚本后立即运行的函数(可选).

只要你提供其中一个,yep和nope都是可选的.

要在check_required.js中加载和执行脚本,请在将modernizr.adc.js附加到页面后添加以下块(代码在required_load.html中):

<script>
  Modernizr.load({
    test: Modernizr.input.required,
    nope: 'js/check_required.js',
    complete: function() {
      init();
    }
  });
</script>
Run Code Online (Sandbox Code Playgroud)

资料来源:http://www.adobe.com/devnet/dreamweaver/articles/using-modernizr.html

  • 谢谢.这种方法看起来很专业 (2认同)

yes*_*lad 5

怎么样

function hasFormValidation() {
  return 'noValidate' in document.createElement('form');
}
Run Code Online (Sandbox Code Playgroud)

资料来源:http://diveintohtml5.info/everything.html#novalidate


Ped*_*ñez 5

导航器存在问题,例如Android(4.4之前的版本),它实现checkValidity(并且此功能实际上检查输入)但是如果某些输入无效,浏览器不会向用户提供任何信息(并发送表单) .

但是,您可以检查是否有任何问题validationMessage.此属性显示浏览器将向用户显示的错误消息.如果checkValidity()是false但是没有validationMessage浏览器没有完整的html5表单验证支持.

我已经完成了这个功能.它需要作为参数的形式中的所有字段:

canValidateFields() {    
    var result = typeof document.createElement( 'input' ).checkValidity == 'function';
    if (result) {
        for (var i = 0; i < arguments.length; i++) {
            var element = document.getElementById(arguments[i]);
            if (!element.checkValidity() && (!element.validationMessage || element.validationMessage === null || element.validationMessage === '')) {
                return false;
            }
        }
    }
    return result;
}
Run Code Online (Sandbox Code Playgroud)

示例:http://jsfiddle.net/pmnanez/ERf9t/2/