input框各种输入框限制总结

限制输入框只能输入正整数

记录日常碰到的输入框限制,以后会慢慢补充

    <input maxlength="3" style="width:70px;height:32px;" type="text" id="btStime" placeholder="限制输入框只能输入正整数" oninput="positive(this)">


js逻辑:应用场景:对于年龄和手机号这些场景有帮助

    function positive(obj) {
        if(obj.value.length == 1) {
            obj.value = obj.value.replace(/[^1-9]/g, '')
        } else {
            obj.value = obj.value.replace(/\D/g, '')
        }
        return obj.value;
    }

输入整数并保留两位小数

    <input maxlength="3" style="width:70px;height:32px;" type="text" id="btStime" placeholder="输入整数并保留两位小数" oninput="inpt(this)">

js逻辑:一般适用于对价格进行限制

    /* 价格限制 */
    function inpt(obj) {
      //禁止录入整数部分两位以上,但首位为0
      obj.value = obj.value.replace(/^([1-9]\d*(\.[\d]{0,2})?|0(\.[\d]{0,2})?)[\d.]*/g, "$1");
      //先把非数字的都替换掉,除了数字和.
      obj.value = obj.value.replace(/[^\d\.]/g, "");
      //必须保证第一个为数字而不是.
      obj.value = obj.value.replace(/^\./g, "0.");
      //保证只有出现一个.而没有多个.
      obj.value = obj.value.replace(/\.{2,}/g, ".");
      //保证.只出现一次,而不能出现两次以上
      obj.value = obj.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
      //只能输入两个小数
      obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, "$1$2.$3");
      return obj.value;
    }

input只能输入正整数,且第一个不能为0,不能输入小数点

    <input maxlength="3" style="width:70px;height:32px;" type="text" id="btStime" placeholder="只能输入正整数,且第一个不能为0,不能输入小数点" oninput="posit(this)">

js逻辑

    /* 限制输入框只能输入正整数 */
    function posit(obj) {
        //禁止录入整数部分两位以上,但首位为0
        obj.value = obj.value.replace(/^([1-9]\d*(\.[\d]{0,2})?|0(\.[\d]{0,2})?)[\d.]*/g, "$1");
        //输入0-9的整数,其他的除外
        obj.value = obj.value.replace(/[^0-9]/g, '')
    }

input验证在文本框输入的只能是数字和字母

    <input
        id="amount"
        maxlength="12"
        type="text"
        placeholder="请输入12位激活密码"
        style="width:70px;height:32px;"
        oninput="amount(this)"
    />

js逻辑:适用场景:输入卡号或者密码都可以适用

    /* 限制输入框只能是数字和字母 */
    function amount(obj) {
        //输入数字和字母,其他的除外
        obj.value = obj.value.replace(/[\W]/g, "")
    }
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值