uniapp input输入框,限制金额输入格式

input只能输入数字和小数点,并且只能有一个小数点,小数点前第一位不能为0

html 复制代码
<u-input v-model="submitMoney" border="none" placeholder="请输入提现金额" @input="handleInput" placeholderStyle="color: #ccc;font-size:32rpx;" fontSize="30">
	<u-text text="¥" slot="prefix" margin="0 3px 0 0" bold size="18" color="#ccc"></u-text>
</u-input>
javascript 复制代码
//限制金额输入格式 
handleInput(e) {
	let newValue = e || ''; // 获取输入框的当前值,注意uView的u-input可能通过event.detail传递值
	let lastChar = newValue.slice(-1); // 获取最后一个字符
	let decimalPosition = newValue.indexOf('.'); // 查找小数点的位置
	let integerPart = ''; // 整数部分
	let decimalPart = ''; // 小数部分
	// 如果输入框为空或者只有一个小数点(非法输入),则重置输入框
	if (newValue === '.' || (newValue.length === 1 && lastChar === '.')) {
		newValue = '';
	} else {
		// 分离整数部分和小数部分
		if (decimalPosition !== -1) {
			integerPart = newValue.slice(0, decimalPosition);
			decimalPart = newValue.slice(decimalPosition + 1);
			// 校验小数部分(最多两位数字)
			if (/\D/.test(decimalPart)) {
				decimalPart = decimalPart.replace(/\D/g, ''); // 移除非数字字符
			}
			if (decimalPart.length > 2) {
				decimalPart = decimalPart.slice(0, 2); // 截取前两位数字
			}
			// 重新组装值
			newValue = integerPart + '.' + decimalPart;
			// 如果整数部分为空且存在小数点,则重置输入框(首位不能是小数点)
			if (integerPart === '' && decimalPart !== '') {
				newValue = '';
			}
		} else {
			// 没有小数点,只校验整数部分(只允许数字)
			if (/\D/.test(newValue)) {
				newValue = newValue.replace(/\D/g, ''); // 移除非数字字符 
			}
		}
	}
	newValue = newValue.replace(/^0+(?=[0-9])/, ''); //去除首位的多个0(如001→1,01→1)

	console.log(newValue)
	this.$nextTick(() => { // 更新数据
		this.submitMoney = newValue;
	})
},
相关推荐
Dreamy smile2 小时前
JavaScript 实现 HTTPS SSE 连接
开发语言·javascript·https
coding随想2 小时前
Web SQL Database API:一段被时代淘汰的浏览器存储技术
前端·数据库·sql
一只程序熊2 小时前
uniapp x 新手入门指南
uni-app
Marshmallowc2 小时前
React 刷新页面 Token 消失?深度解析 Redux + LocalStorage 数据持久化方案与 Hook 避坑指南
javascript·react·数据持久化·redux·前端工程化
Dreamy smile2 小时前
vue3 vite pinia实现动态路由,菜单权限,按钮权限
前端·javascript·vue.js
翱翔的苍鹰2 小时前
智谱(Zhipu)大模型的流式使用 response.iter_lines() 逐行解析 SSE 流
服务器·前端·数据库
未来之窗软件服务2 小时前
仙盟创梦IDE-集成开发测试:自动解析驱动的多线路自动化测试
前端·测试自动化·仙盟创梦ide·东方仙盟
天天睡大觉3 小时前
python命名规则(PEP8编码规则)
开发语言·前端·python
2501_944521593 小时前
Flutter for OpenHarmony 微动漫App实战:底部导航实现
android·开发语言·前端·javascript·redis·flutter·ecmascript