0

I need the validation on each key press

<strike><input type="number"  value="" id="phno" name="num" onkeydown="return isNumber()" /></strike>

function isNumber(){
   var s= document.getElementById("phno").value;
   if(isNaN(phno)){
     alert("mistmatch");
   }
}

How do I validate on each key press (probably the keyup event)

Jez D
  • 1,461
  • 2
  • 25
  • 52

3 Answers3

1

You can try this

<input type="text" id="myTextBox" />

The script

$("#myTextBox").on('keydown', function(e) {
  var key = e.keyCode ? e.keyCode : e.charCode;
  var value = $(this).val();
  if (key > 57 && ((key == 190 && value.indexOf('.') >= 0) || key != 190)) {
    e.preventDefault();
  }
});

This will allow users to input decimal value or whole numbers.

eman.lodovice
  • 192
  • 1
  • 6
1

Try this:

Pure JS

script

var digits = function(box) {
    box.value = box.value.replace(/[^0-9]/g, '');
};

html

<input type="text" placeholder="Digits only" onkeyup="digits(this)"/>

JQuery

script

$(function(){
    $('.digits').on('input', function(e){
        this.value = this.value.replace(/[^0-9]/g, '');
    });
});

html

<input type="text" placeholder="Digits only" class="digits"/>
0

Use this DOM

<input type='text' onkeypress='validate(event)' />

And this script

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

Hope it Helps

Khaleel
  • 1,212
  • 2
  • 16
  • 34