验证带有2个小数点的浮点形式的输入表单

Validate inputform for float with 2 decimal

本文关键字:输入 表单 2个 小数点 验证      更新时间:2024-03-13

我想用Javascript检查用户在html中输入的带有2个小数点的浮点值。只允许使用0-9和1 x","。如果没有",",我想插入",00"。

例如:

1234->1234,00

123f->123,00

1234,12->1234,12

123a4,15->1234,15

12341525,23->12341525,23

很好的是增加一个分离器4000,但有很好

12341525,23->12.341.525,23

正因为如此,我不能使用:

<input type="number" name="abc" step="0.01">

这将检查逗号是否多于一个。如果逗号后面没有逗号或数字不够,它将添加逗号和零。它还检查分数部分和积分部分是否为数字。

x = document.getElementById("abc").value;
if(x.indexOf(",") != x.lastIndexOf(",")) {
  //Invalid, there is more than one comma
} else {
  var comma = x.indexOf(",");
  if(comma == -1) {
    x = x.concat(",00"); // No comma
  } else if(comma == x.length - 1) {
    x = x.concat("00"); // comma, no digits after it though
  } else if(comma == x.length - 2) {
    x = x.concat("0"); // comma with 1 digit after it
  }
  if(comma <= x.length - 3) { 
    var parts = x.split(",");
    if(isNaN(parts[0]) || isNaN(parts[1])) {
      //Invalid, either the integral part or the fractional part is not a number
    }
  } else {
    // Invalid, the comma comes before more than two digits
  }
}

我认为这段代码正是您想要的。它还设置了一千个分隔符。

请注意,十进制分隔符通常是一个点,千位分隔符通常为逗号。;)

也许有一种较短的方法只使用正则表达式。。。但是下面的代码是有效的。

<input id="foo" type="text" onchange="formatNumber();" onkeyup="onlyNumbers();">
<script>
function formatNumber(){
    // define separators
    thousandSep=".";
    decimalSep=",";
    // get the input
    n=document.getElementById("foo").value;
    // Format decimals
    n=parseFloat(n).toFixed(2);
    decimals=decimalSep+n.substr(n.length-2);
    // Temporarly remove the decimals and count how many thousand groups there is
    n=parseInt(n).toString();
    thousandGroups=parseInt(Math.ceil(n.length/3));
    //Place the thousand separator between each group of 3 digits
    for(i=1;i<thousandGroups;i++){
        j=i-1;
        n=n.substr(0,n.length-(3*i+j))+thousandSep+n.substr(n.length-(3*i+j));
    }
    // return the formated number
    document.getElementById("foo").value=n+decimals;
}
function onlyNumbers(){
    n=document.getElementById("foo").value;
    // Check if last keyboard input is a digit... Accepts dots
    if(n.substr(n.length-1).search(/^['d'.]/i)!=-1){
        document.getElementById("foo").value=n;
    }else{
        document.getElementById("foo").value=n.substr(0,n.length-1)
    }
}
</script>