Diasline Diasline - 2 years ago 66
Javascript Question

Input Validation - How to allow backspace to work in my method

I have a function that allow input field to receive numbers and the decimal point. How can I allow the backspace key as well ?

function verifierCaracteres(event) {

var keyCode = event.which ? event.which : event.keyCode;
var touche = String.fromCharCode(keyCode);

var champ = document.getElementById('mon_input');

var caracteres = '.0123456789';

if(caracteres.indexOf(touche) >= 0) {
champ.value += touche;


And my HTML:

<input type="text" name="Patient_Amount" id="mon_input" onkeypress="verifierCaracteres(event); return false;"/>

Answer Source

Use keyCode == 8 in your validation. 8 is the keycode for backspace.

Really, this is a job for regex and replace. That is how I typically go about this process. Here is an example.

function verifierCaracteres() {
    var inputEle = document.getElementById("mon_input");
    var value = inputEle.value;
    inputEle.value = value.replace(/([^0-9\.])+/g,'');

This will remove all characters from input that are not 0-9 or .

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download