0

Here is my JS

function validate(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();
  }
}

the script is for the input tag only can type number only.

It works well on google chrome, but on firefox 15.0 backspace, delete, arrow key is not working

This is bug of firefox, or something wrong with my script?

Sieryuu
  • 1,510
  • 2
  • 16
  • 41

2 Answers2

2

The reason is Chrome and IE doesn't fire the keypress event for these special keys (backspace, delete, arrow key).

But for Firefox, the event will be fired, and failed match the regex, so theEvent.preventDefault() will be executed.

xdazz
  • 158,678
  • 38
  • 247
  • 274
1

As xdazz said:

var key = theEvent.keyCode || theEvent.which;

key is the ASCII code of the pressed key. Backspace is 8, delete is 46.

var key = theEvent.keyCode || theEvent.which;

now that code is converted to a character. Backspace and delete keys do not map to a number, so the regular expression causes the default action to be prevented.

The strategy is flawed because you don't care what the value of the field is until it is submitted to the server, so validate the content when the user leaves the field and when the form is submitted (and again at the server, always).

The user can put data into a form field in many ways other than key presses, so use the value of the field (not the key that was pressed) to validate. It's far simpler and less error prone.

RobG
  • 142,382
  • 31
  • 172
  • 209