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

一、基本结构 

<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;
				})
			},

猜你喜欢

转载自blog.csdn.net/m0_46846526/article/details/120022751
今日推荐