vue 文本输入框只允许输入字母、数字、不允许输入特殊字符

67 篇文章 7 订阅

一、基本结构 

<input type="text" v-model="note" maxlength="18">
<script>
export default {
  data () {
    return {
      note: '',
    }
  }
}
</script>

二、监听表单输入的内容 

(1) 只允许输入字母 

  watch: {
    note (newValue, oldValue) {
      console.log(newValue)
      this.note = newValue.replace(/[\u4e00-\u9fa5/\s+/]|[`~!@#$%^&*() \\+ =<>?"{}|, \\/ ;' \\ [ \] ·~!@#¥%……&*()—— \\+ ={}|《》?:“”【】、;‘’,。、_.-:]/g, "")
    }
  },

(2)只能输入汉字、英文、数字 

  watch: {
     note (newValue, oldValue) {
      console.log(newValue)
      this.note = newValue.replace(/[^a-zA-Z0-9\u4E00-\u9FA5]/g, "")
    }
  },

(3) 只允许输入数字

  watch: {
      note (newValue, oldValue) {
      console.log(newValue)
      this.note = newValue.replace(/[^\d]/g, "")
    }
  },

(4)只允许输入数字、字母

  watch: {
     note (newValue,oldValue) {
      console.log(newValue)
      this.note = newValue.replace(/[\u4e00-\u9fa5/\s+/]|[^a-zA-Z0-9\u4E00-\u9FA5]/g, "")
    }
  },

 注意 没有采用添加 input事件 

三、使用方法的缺陷:

<input type="text" v-model="note" maxlength="18" @input="filter">

 methods: {
    filter (e) {
      console.log(e)
      this.note = e.data.replace(/[\u4e00-\u9fa5/\s+/]|[`~!@#$%^&*() \\+ =<>?"{}|, \\/ ;' \\ [ \] ·~!@#¥%……&*()—— \\+ ={}|《》?:“”【】、;‘’,。、_.-:]/g, "")
    }
  },

(1)只能输入一个字母内容 

 (2)采用输入法输入多个字符时会报错   而且用拼音输入法按回车键也可以显示其他数字或字符

补充 校验手机号

    test () {
      console.log(/^1[34578]\d{9}$/.test(this.mobile))
    }

 只允许输入数字、点 保留两位小数

	checkNumber(e) {
				let val = e.target.value.replace(/(^\s*)|(\s*$)/g, "")
				var reg = /[^\d.]/g
							
				// 只能是数字和小数点,不能是其他输入
				val = val.replace(reg, "")
				// // 保证第一位只能是数字,不能是点
				val = val.replace(/^\./g, "");
				// // 小数只能出现1位
				val = val.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
				// // 小数点后面保留2位
				val = val.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');
				// console.log(val);
				this.$nextTick(() => {
					this.form.price = val;
				})
			},

  • 10
    点赞
  • 46
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值