简体   繁体   中英

How can I validate input[type=“number”] in old browsers?

I like HTML5 constraint validation as it provides a defined and standard syntax to specify how an input should be allowed and how it shouldn't and prevents different implementations across projects.

However the big issue is that many people still use old browsers such as IE8 because many people still use Windows XP and IE8 is the last update they get automatically.

How can I validate through javascript this type of input and keep using the HTML5 syntax?

You can use polyfills to add support of input[type="number"] when unsupported by the browser such as Webshims .

If you only want to validate them, I made this function (it should support all constraint attibutes for numbers), it works fine for me but you're welcomed to point any mistake I made:

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM