export default {
isNumber : function (checkVal){
var reg = /^-?[1-9][0-9]?.?[0-9]*$/;
return reg.test(checkVal);
},
/**
* @description 小数点前后位数限制
* “当前输入的值”、“小数点前限制的位数”、“小数点后限制的位数”
*/
limitByPoint: function(val, limitBeforePoint, limitAfterPoint) {
const pointNum = (val.includes(".") && val.match(/\./g).length) || 0; // 小数点数量
let limitValue = '0';
if (pointNum === 0) {
// 不包含小数点
// 移除开头的0,除非值只有一位且是0
val = val.replace(/^0+/, (m) => (m.length === val.length && m.length === 1 ? m : ''));
// 如果值仍然为0且长度大于1位,则设置为空字符串(或根据需要设置默认值)
if (val === '0' && val.length > 1) {
val = '';
}
if (val.length > limitBeforePoint) {
limitValue = val.substring(0, limitBeforePoint);
} else {
limitValue = val;
}
} else if (pointNum === 1) {
// 小数点数量为1
const pointIndex = val.indexOf("."); // 小数点所在位置的索引
const valueBeforePoint = val.substring(0, pointIndex); // 小数点前的数
const valueAfterPoint = val.substring(pointIndex + 1); // 小数点后的数
// 限制小数点前的位数
if (valueBeforePoint.length > limitBeforePoint) {
console.log(valueBeforePoint.substring(0, limitBeforePoint),valueAfterPoint)
limitValue = valueBeforePoint.substring(0, limitBeforePoint) + "." + valueAfterPoint;
uni.showToast({
title: "请输入正确的值,小数点前的数值位数最大为"+limitBeforePoint+"位",
icon: "none",
});
}
// 限制小数点后的位数
if (valueAfterPoint.length > limitAfterPoint) {
limitValue = valueBeforePoint + "." + valueAfterPoint.substring(0, limitAfterPoint);
uni.showToast({
title: "请输入正确的值,小数点位数只能保留"+limitAfterPoint+"位",
icon: "none",
});
} else {
limitValue = val; // 如果没有超出小数点后的限制,则保持原值
}
} else {
// 小点数量大于1,属于错误值
uni.showToast({
title: "请输入正确的值",
icon: "none",
});
limitValue = ''; // 清空值或设置为默认值
}
return limitValue;
}
}
在页面引用
<template>
<form>
<view class="uni-form-item">
<view class="mb10px color-6a6a6a">核销借款</view>
<input type="number" placeholder="请输入核销借款" v-model="form.unitPrice" @input="limitByPoint($event,'unitPrice',8,3)" />
</view>
</form>
</template>
<script>
import checker from "@/utils/checker.js"
export default {
data() {
return {
form: {
id: null,
unitPrice:0
}
}
},
methods: {
// “当前输入的值”、“key名称”、“小数点前限制的位数”、“小数点后限制的位数”,
limitByPoint(event, formVal,beforNum,afterNum) {
let val = graceChecker.limitByPoint(event.detail.value, beforNum, afterNum)
this.$nextTick(() => {
this.form[formVal]=val
})
}
}
}
</script>