input框校验只能输入数字和小数点方法

   // 只能输入数字且只有一位小数
    proving(item) {
      // this.form[item] 是input的值
      // 先把非数字的都替换掉,除了数字和.
      this.form[item] = this.form[item].replace(/[^\d.]/g, "");
      // 必须保证第一个为数字而不是.
      this.form[item] = this.form[item].replace(/^\./g, "");
      // 保证只有出现一个.而没有多个.
      this.form[item] = this.form[item].replace(/\.{2,}/g, "");
      // 保证.只出现一次,而不能出现两次以上
      this.form[item] = this.form[item]
        .replace(".", "$#$")
        .replace(/\./g, "")
        .replace("$#$", ".");
      let index = -1;
      for (let i in this.form[item]) {
        if (this.form[item] === ".") {
          index = i;
        }
        if (index !== -1) {
          if (i - index > 1) {
            this.form[item] = this.form[item].substring(
              0,
              this.form[item].length - 1
            );
          }
        }
      }

随手保存下,下次方便使用

posted @ 2020-04-13 17:27  zhupan  阅读(3448)  评论(0编辑  收藏  举报