2013-09-25 36 views
0

我喜欢HTML5约束验证,因为它提供了一个定义的和标准的语法来指定应该如何允许输入以及如何不允许输入,并防止跨项目的不同实现。如何在旧版浏览器中验证输入[type =“number”]?

然而,最大的问题是许多人仍然使用旧的浏览器,如IE8,因为许多人仍然使用Windows XP,而IE8是他们自动获得的最新更新。

如何通过JavaScript验证此类型的输入并继续使用HTML5语法?

+0

https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-browser-Polyfills#web-forms – Bergi

回答

1

当浏览器不支持等浏览器不支持的情况下,您可以使用polyfills添加输入[type =“number”]的支持。

如果你只是想验证他们,我做了这个功能(它应该支持所有的约束attibutes为数字),它工作正常,但对我来说你欢迎我点的任何错误:

function validateNumbers(){ 
    var returner = true; 
    $(this).find('input[type="number"]').each(function(i){ 
     var valor = $(this).val(); 
     var max = $(this).attr("max"); 
     var min = $(this).attr("min"); 
     var step = $(this).attr("step"); 
     var decimals = 0; 
     if(typeof step == 'undefined'){ 
      step = "1"; 
     } 
     if(typeof valor != 'undefined' && typeof valor.split(".")[1] != 'undefined' && typeof step.split(".")[1] != 'undefined') { 
      decimals = (valor.split(".")[1].length>step.split(".")[1].length)?valor.split(".")[1].length:step.split(".")[1].length; 
     } else if((typeof valor == 'undefined'||typeof valor.split(".")[1] == 'undefined') && typeof step.split(".")[1] != 'undefined'){ 
      decimals = step.split(".")[1].length; 
     } else if((typeof step.split(".")[1] == 'undefined') && typeof valor != 'undefined' && typeof valor.split(".")[1] != 'undefined'){ 
      decimals = valor.split(".")[1].length; 
     } 
     var multiplier = "1"; 
     for (var i=0;i<decimals;i++){ 
      multiplier += "0"; 
     } 
     valor = valor*multiplier; 
     max = max*multiplier; 
     min = min*multiplier; 
     step = step*multiplier; 
     if(isNaN(valor)||(!isNaN(max)&&valor>max)||(!isNaN(min)&&valor<min)||(!isNaN(step)&&(valor-(isNaN(min)?0:min))%step!=0)){ 
      //$(this).parent().addClass("error"); or however you show errors 
      returner = false; 
     } 
    }); 
    return returner; 
} 
相关问题