Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 268
Anshuma Avatar asked Jan 04 '23 15:01

Anshuma


2 Answers

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.

like image 77
Hubert Grzeskowiak Avatar answered Jan 07 '23 19:01

Hubert Grzeskowiak


You are passing 1 char each time to the myfunction function, so you cannot check the whole value with /^[0-9]+([.][0-9]+)?$/ regex to make sure your format is adhered to.

Check if you input digits, or only allow typing a dot if there is no dot in the input field yet:

<input type="text" id="test" onkeypress="return myfunction(event);" />
<script>
function myfunction(e) {
  return e.charCode === 0 || ((e.charCode >= 48 && e.charCode <= 57) || (e.charCode == 46 && document.getElementById("test").value.indexOf('.') < 0));
}
</script>
like image 44
Wiktor Stribiżew Avatar answered Jan 07 '23 19:01

Wiktor Stribiżew