Skip to content
Advertisement

Regex to allow only numbers and decimals not working in Javascript

I am trying this below code and the regex isn’t working and it is allowing all the characters in the input box.

Desired: Input text box should not accept any other character other than numbers and decimal point.

<html>
<body>
    <input type="text" onkeypress="myfunction(event);"></input>
<script>
    function myfunction(e){
         var p = new RegExp(/^[0-9]+([.][0-9]+)?$/);
         return e.charCode === 0 ||   p.test(String.fromCharCode(e.charCode));      
    }
</script>
</body>
</html>

Advertisement

Answer

Here’s an alternative way. I’m using the oninput event that is triggered on every value change by user (not only key presses). I’m saving the last valid value and restoring it whenever the new value is invalid.

<input type="text" id="test1" oninput="validateNumber(this);" />
<script>
var validNumber = new RegExp(/^d*.?d*$/);
var lastValid = document.getElementById("test1").value;
function validateNumber(elem) {
  if (validNumber.test(elem.value)) {
    lastValid = elem.value;
  } else {
    elem.value = lastValid;
  }
}
</script>

In contrast to most other answers here this works flawlessly with all input techniques like drag’n’drop, copy’n’paste etc. It also supports special control keys like Ctrl+a (for selecting contents), Pos1, End and so on.

Advertisement