JS判斷輸入的是金額或者數字
阿新 • • 發佈:2019-02-07
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<input type="text" id ="test" name="test" onkeyup="clearNoNum(this)"/>
<script>
function clearNoNum(obj){
obj.value = obj.value.replace(/[^\d.]/g,""); //清除"數字"和"."以外的字元
obj.value = obj.value.replace(/^\./g,""); //驗證第一個字元是數字而不是
obj.value = obj.value.replace(/^00/g,""); //驗證前兩位不能同時為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\d).*$/,'$1$2.$3');
}
</script>
</body>
</html>
<html>
<body>
<h1>My First Web Page</h1>
<input type="text" id ="test" name="test" onkeyup="clearNoNum(this)"/>
<script>
function clearNoNum(obj){
obj.value = obj.value.replace(/[^\d.]/g,""); //清除"數字"和"."以外的字元
obj.value = obj.value.replace(/^\./g,""); //驗證第一個字元是數字而不是
obj.value = obj.value.replace(/^00/g,""); //驗證前兩位不能同時為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\d).*$/,'$1$2.$3');
}
</script>
</body>
</html>