vue限制文本输入框只允许输入字母、数字、禁止输入特殊字符
更新时间:2023年10月09日 10:37:17 作者:奥特曼
这篇文章主要介绍了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;
})
},到此这篇关于vue限制文本输入框只允许输入字母、数字、不允许输入特殊字符的文章就介绍到这了,更多相关vue限制文本输入框输入数字内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
Vue+vite创建项目关于vite.config.js文件的配置方法
Vue项目创建时,我们见过vue-cli 创建项目和webpack 创建项目等方式,这篇文章主要介绍了Vue+vite创建项目关于vite.config.js文件的配置方法,需要的朋友可以参考下2023-06-06
在vue中,v-for的索引index在html中的使用方法
下面小编就为大家分享一篇在vue中,v-for的索引index在html中的使用方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2018-03-03


最新评论