JavaScript to allow only numbers, comma, dot, backspace

javascript, regex

Solution

Try this code:

function isNumber(evt) {
          var theEvent = evt || window.event;
          var key = theEvent.keyCode || theEvent.which;
          key = String.fromCharCode(key);
          if (key.length == 0) return;
          var regex = /^[0-9.,\b]+$/;
          if (!regex.test(key)) {
              theEvent.returnValue = false;
              if (theEvent.preventDefault) theEvent.preventDefault();
          }
}

Problem

i wrote a javascript function to allow only numbers, comma, dot like this ``` function isNumber(evt) { var theEvent = evt || window.event; var key = theEvent.keyCode || theEvent.which; key = String.fromCharCode(key); var regex = /^[0-9.,]+$/; if (!regex.test(key)) { theEvent.returnValue = false; if (theEvent.preventDefault) theEvent.preventDefault(); } } ``` but if i want to remove any number form text box.. backspace is not working. then i changed regex code as "`var regex = /^[0-9.,BS]+$/;`" still i am not able to use backspace in textbox.even i cant use left and right keys on textbox is i am doing wrong? can anyone help... thanks. (when I used "BS" in regex instead of backspace its allowing "B","S" Characters in textbox..)

Original source