input輸入框數字限制
阿新 • • 發佈:2019-02-09
正則表示式驗證輸入框的內容
// 單價 只能輸入數字和小數點,且必須數字開頭並大於或者等於1,限制最多三位小數,小數點為最後一位時,失去焦點時自動截掉
<input type="text" value="" name="price" onkeyup="ValidateNum1(this)" onblur="toDecimal(this)" placeholder="請輸入單價" maxlength="8"/>
// 數量 只能輸入正整數
<input type="text" class="set_val" name="money" id="" onkeyup="ValidateNum3(this)" placeholder="請輸入數量" maxlength="7"/>
// 總價 只能輸入數字和小數點,且必須數字開頭並大於或者等於1,限制最多兩位小數,小數點為最後一位時或者輸入的為正整數時,失去焦點時自動補兩位小數
<input type="text" class="set_val" name="totalMoney" id="" onkeyup="ValidateNum2(this)" onblur="toDecimal2(this)" maxlength="5" placeholder="請輸入總價" />
// 驗證輸入內容是否合法
function ValidateNum1 (obj) {
obj.value = obj.value.replace(/[^\d.]/g,""); //清除"數字"和"."以外的字元
obj.value = obj.value.replace(/^\./g,""); //驗證第一個字元是數字而不是.
obj.value = obj.value.replace(/^0/g,""); //驗證第一個字元是數字而不是0
obj.value = obj.value.replace(/^0+$/g,"");//若以0開頭且連續鍵入多個0時,替換空
obj.value = obj.value.replace(/\.{2,}/g ,"."); //只保留第一個. 清除多餘的
obj.value = obj.value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d\d).*$/,'$1$2.$3'); //只能輸入三個小數
}
function ValidateNum2(obj) {
obj.value = obj.value.replace(/[^\d.]/g,""); //清除"數字"和"."以外的字元
obj.value = obj.value.replace(/^\./g,""); //驗證第一個字元是數字而不是.
obj.value = obj.value.replace(/\.{2,}/g,"."); //只保留第一個. 清除多餘的
obj.value = obj.value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3'); //只能輸入兩個小數
}
function ValidateNum3(obj) {
obj.value = obj.value.replace(/[^\d]/g,""); //清除"數字"以外的字元
obj.value = obj.value.replace(/^0/g,""); //驗證第一個字元是數字而不是0 最低賠率只能為1
obj.value = obj.value.replace(/^0+$/g,"0");//若以0開頭且連續鍵入多個0時,只保留一個0
}
function toDecimal(obj){
var f = parseFloat(obj.value);
if (isNaN(f)) {
return false;
}
obj.value = f;
}
// 退水自動補足小數點後兩位
function toDecimal2(obj){
var f = parseFloat(obj.value);
if (isNaN(f)) {
return false;
}
var s = f.toString();
var rs = s.indexOf('.');
if (rs < 0) {
rs = s.length;
s += '.';
}
while (s.length <= rs + 2) {
s += '0';
}
obj.value = s;
}