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

时间:2025-01-22 07:33:33

一、基本结构 

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

二、监听表单输入的内容 

(1) 只允许输入字母 

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

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

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

(3) 只允许输入数字

  watch: {
      note (newValue, oldValue) {
      (newValue)
       = (/[^\d]/g, "")
    }
  },

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

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

 注意 没有采用添加 input事件 

三、使用方法的缺陷:

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

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

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

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

补充 校验手机号

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

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

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