Vue中form表单的手机号码输入优化

最终效果

在这里插入图片描述

  • 只能输入数字
  • 4位 7位空格切割

实现

<template>
  <div class="nearshopCharge">
	<div class="main_form_pane">
      <div class="form_item">
        <label for="消费者手机号码">
          消费者手机号码
          <span class="red">*</span>
        </label>
        <div class="input_item">
          <input class="text" maxlength="13" v-model="phone" placeholder="请填写用户的手机号码" type="tel" />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "nearshopCharge",
  data() {
    return {
      imgtop: require(`../../assets/public/Vue-assets/img/buy_song/pic55.png`),
      num: 0,
      selectXy: false,
      name: "",
      phone: "",
      money: "",
      inputKeyVal: ""
    };
  },
  watch: {
    phone(newValue, oldValue) {
      //Remove Chinese
      this.phone = this.phone.replace(/[\u4e00-\u9fa5]/g, "");
      //Remove English
      this.phone = this.phone.replace(/[A-Za-z]+$/g, "");
      //Remove symbol
      let reg = new RegExp(
        "[`~!@#$^&*()=|{}':;',\\[\\].<>《》/?~!@#¥……&*()——|{}【】‘;:”“'。,、\\_\\+\\-\\%?]"
      );
      this.phone = this.phone.replace(reg, "");
      // Remove blank
      if (this.inputKeyVal == "Space") {
        this.phone = oldValue
        this.inputKeyVal = ''
      }
      // Delete or Input
      if (newValue.split("").length < oldValue.split("").length) {
        return false;
      }

      // Split numbers
      let phoneStr = newValue.split("");
      // Insert blank in 4 , 9 , 14
      if (newValue.split("").length === 4) {
        phoneStr.splice(3, 0, " ");
        this.phone = phoneStr.join("");
      } else if (newValue.split("").length === 9) {
        phoneStr.splice(8, 0, " ");
        this.phone = phoneStr.join("");
      } else if (newValue.split("").length === 14) {
        this.phone = oldValue.split("");
      }
    }
  },
  mounted() {
    addEventListener("keydown", val => {
      this.inputKeyVal = val.code;
    });
  }
};
</script>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值