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;
	})
},
相关推荐
憧憬成为web高手5 小时前
ACTF 12307复现
前端·bootstrap·html
wordbaby5 小时前
Axios 上传大文件崩溃:鸿蒙 RNOH 下 XHR 返回空响应头引发的"假失败"
前端·react native
wordbaby6 小时前
React Native 列表分页实战:下拉刷新与上拉加载的工程化方案
前端·react native
wordbaby6 小时前
脱离 Tab 栏的艺术:React Native 全屏子页面的导航架构实践
前端·react native·harmonyos
陈随易7 小时前
Redis 8.8发布,一定要更新
前端·后端·程序员
wordbaby7 小时前
React Native 新架构落地鸿蒙:跨三端政务级应用的工程实践与深度复盘
前端·react native·harmonyos
晓说前端7 小时前
第一篇:为什么学TypeScript?—— 优势、场景与环境搭建
javascript·ubuntu·typescript
excel8 小时前
为什么我推荐使用 Termius:现代 SSH 工具的完整体验
前端·后端
ZC跨境爬虫8 小时前
模块化烹饪小程序开发日记 Day7:(菜谱详情接口开发与JSON数据读取全流程)
前端·javascript·css·ui·微信小程序·json
এ慕ོ冬℘゜8 小时前
JS 前端基础面试题
开发语言·前端·javascript