<template>
<view>
<input
v-model="inputValue"
@input="handleInput"
type="text"
placeholder="请输入" />
<span v-if="!isValidInput" style="color: red;">
请输入0.00-100.00之间的数(最多两位小数)
</span>
</view>
</template>
<script>
export default {
data() {
return {
inputValue: '',
isValidInput: true // 初始化为 true
};
},
methods: {
handleInput() {
//使用正则校验 匹配0.00-100.00之间的数,最多两位小数
const regex = /^(100(\.00?)?|(\d{0,2}(\.\d{0,2})?)?)$/;
if (!regex.test(this.inputValue)) {
this.inputValue = ''; //当超出 校验规则,直接清空 input 里面的值,并提示
this.isValidInput = false; // 设置为 false
} else {
this.isValidInput = true; // 设置为 true
}
}
}
};
</script>
前端 input 框实现 0.00-100.00 之间的数(正则)超出内容后将直接清空 input 内容
于 2024-02-19 09:49:38 首次发布
本文介绍了如何在Vue.js组件中使用v-model和正则表达式实现输入框的数值验证,确保用户输入的数值在0.00到100.00范围内,且最多保留两位小数。
摘要由CSDN通过智能技术生成