4

谁能帮我找到一个解决方案来验证文本字段以接受有效的十进制数字。我尝试了类似的东西

function fun_AllowOnlyAmountAndDot(txt) {
    if (event.keyCode > 47 && event.keyCode < 58 || event.keyCode == 46) {
        var txtbx = document.getElementById(txt);
        var amount = document.getElementById(txt).value;
        var present = 0;
        var count = 0;

        if (amount.indexOf(".", present) || amount.indexOf(".", present + 1)); {
            // alert('0');
        }

        /*if(amount.length==2)
              {
                if(event.keyCode != 46)
                return false;
              }*/
        do {
            present = amount.indexOf(".", present);
            if (present != -1) {
                count++;
                present++;
            }
        }
        while (present != -1);
        if (present == -1 && amount.length == 0 && event.keyCode == 46) {
            event.keyCode = 0;
            //alert("Wrong position of decimal point not  allowed !!");
            return false;
        }

        if (count >= 1 && event.keyCode == 46) {
            event.keyCode = 0;
            //alert("Only one decimal point is allowed !!");
            return false;
        }
        if (count == 1) {
            var lastdigits = amount.substring(amount.indexOf(".") + 1, amount.length);
            if (lastdigits.length >= 4) {
                //alert("Two decimal places only allowed");
                event.keyCode = 0;
                return false;
            }
        }
        return true;
    } else {
        event.keyCode = 0;
        //alert("Only Numbers with dot allowed !!");
        return false;
    }
}
4

2 回答 2

1

If you only want decimal numbers, then a simple regex suffices:

function validateNumber(num) {
  return /^-?[1-9][0-9]*(.[0-9]+)?$/.test(num);
}

In English, this means

  • ^: Start at the beginning of the input.
  • -?: Optional negative sign.
  • [1-9]: The first character must be a digit in the range 1-9 (i.e. no leading zeros).
  • [0-9]* That must be followed by zero or more digits in the range 0-9.
  • (.[0-9]+)?: That can optionally be followed by a decimal point and one or more digits in the range 0-9.
  • $: One you get here, it must be the end of the number.
于 2013-05-27T20:40:46.047 回答
1

让我们简单地做:

var txtbx = document.getElementById("txt");

txtbx.addEventListener("keyup",function(e) {
  var parsed = parseFloat(txtbx.value)||0;
  if(parsed!=txtbx.value) txtbx.value = parsed;
});
于 2013-05-27T21:25:44.500 回答