如何检查浏览器是否具有内置的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)
小智 7
你可以使用Modernizr javascript http://www.modernizr.com/来做到这一点.你可以从这篇文章html5表格验证modernizr safari获得帮助.您还可以利用modernizr负载
Modernizr.load()的基本语法是将具有以下属性的对象传递给它:
只要你提供其中一个,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
怎么样
function hasFormValidation() {
return 'noValidate' in document.createElement('form');
}
Run Code Online (Sandbox Code Playgroud)
资料来源:http://diveintohtml5.info/everything.html#novalidate
导航器存在问题,例如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/