适配android和ios的文本框输入限制

246 阅读1分钟

代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <input type="text" id="btn" maxlength="25">
</body>
<script>
    var btn = document.getElementById("btn");
    btn.onblur=function(){
        var val = btn.value;
        if(/^[0-9]{11}$/.test(val)){
            console.log("卡号不能为11位");
        }else {
            console.log("正确");
        }
    }
    var tel = document.getElementById('btn');
        tel.onkeyup = function () {
            this.value = this.value.replace(/[^\d.]/g, "");  //只能输入数字或者小数点 
            this.value = this.value.replace(/\.{2,}/g, "."); //只能输入一个点  清除多余的 
            this.value = (this.value.match(/\d{0,7}(\.\d{0,2})?/) || [''])[0]; // 只能以数字开头(且最多只能输入7为整数)小数点后只能留2位;
            if (this.value.indexOf(".") < 0 && this.value != "") {  //如果没有小数点,首位不能为类似于 01、02的金额    
                this.value = parseFloat(this.value);
            }
        }
        var u = navigator.userAgent, app = navigator.appVersion;
        var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //android终端或者uc浏览器   
        var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端   
        if (isiOS) {
            $("input[type='tel']").attr('type', 'number');
        }
</script>
</html>