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;
	})
},
相关推荐
橙序员小站1 小时前
Agent Skill 是什么?一文讲透 Agent Skill 的设计与实现
前端·后端
炫饭第一名3 小时前
速通Canvas指北🦮——基础入门篇
前端·javascript·程序员
王晓枫4 小时前
flutter接入三方库运行报错:Error running pod install
前端·flutter
符方昊4 小时前
React 19 对比 React 16 新特性解析
前端·react.js
ssshooter4 小时前
又被 Safari 差异坑了:textContent 拿到的值居然没换行?
前端
曲折4 小时前
Cesium-气象要素PNG色斑图叠加
前端·cesium
Forever7_4 小时前
Electron 淘汰!新的桌面端框架 更强大、更轻量化
前端·vue.js
Angelial4 小时前
Vue3 嵌套路由 KeepAlive:动态缓存与反向配置方案
前端·vue.js
jiayu5 小时前
Angular学习笔记24:Angular 响应式表单 FormArray 与 FormGroup 相互嵌套
前端
jiayu5 小时前
Angular6学习笔记13:HTTP(3)
前端