input进行限制数字,小数点,及小数点后数字个数等问题

1,639 阅读1分钟

只能输入数字

this.inputValue = this.inputValue.replace(/[^\d]/g, ""); // 清除"数字"以外的字符 

只能输入数字和小数点

this.inputValue = this.inputValue.replace(/[^\d.]/g, ""); // 清除"数字"和"."以外的字符

限制小数点输入个数,只能输入一个小数点

this.inputValue = this.inputValue.replace(/\.{2,}/g, "."); // 不能连续输入两个及以上小数点
this.inputValue = this.inputValue
	.replace(".", "$#$")
	.replace(/\./g, "")
	.replace("$#$", "."); // 只保留第一个".", 清除多余的"."

只能输入一位小数点

this.inputValue = this.inputValue.replace(
	/^(-)*(\d+)\.(\d).*$/,
	"$1$2.$3"
); // 只能输入一位小数

只能输入两位小数点

this.inputValue = this.inputValue.replace(
	/^(-)*(\d+)\.(\d\d).*$/,
	"$1$2.$3"
); // 只能输入两位小数

只能输入三位小数点,之后的以此类推

this.inputValue = this.inputValue.replace(
	/^(-)*(\d+)\.(\d\d\d).*$/,
	"$1$2.$3"
); // 只能输入三位小数

如果有小数点是可以输入0.1,0.001等,但是没有小数点就不能输入0开头的数字,即不能输入01,02等。

if (
	this.inputValue &&
	this.inputValue.indexOf(".") < 0 &&
	this.inputValue != ""
) {
	this.inputValue = parseFloat(this.inputValue);
	this.inputValue = this.inputValue + ""; // 变回为字符串
} // 如果没有小数点,首位不能为类似于 01、02的值

当有小数点位数限制时,例如小数点后可以输入六位小数

	// 输入过程中,只能输入六位小数且六位小数都为零,则清空小数点和后面的六个零(如果输入完成了只输入四个零,则在blur事件中处理)
if (
	this.inputValue.indexOf(".") > 0 &&
	this.inputValue.length - this.inputValue.indexOf(".") > 6
) {
	let str = this.inputValue.slice(
		this.inputValue.indexOf("."),
		this.inputValue.length
	);
	if (str / 1 <= 0) {
		this.inputValue = this.inputValue.replace(str, "");
	}
}

在 blur 事件中,如果小数点后面全是零,则清空小数点和后面的零

if (this.inputValue.indexOf(".") > 0) {
	let str = this.inputValue.slice(
		this.inputValue.indexOf("."),
		this.inputValue.length
	);
	if (str / 1 <= 0) {
		this.inputValue = this.inputValue.replace(str, "");
	}
}