0

I have the following function attached to the onkeypress event of a textbox. It only allows one integer after decimal point numbers(for eg:allow .2,1.2,12.3, not allow 2.34,.24,..,2..3,) and integers to be entered into the textbox.I want to prevent pasting alphabets special characters etc.using the following code Restricting input to textbox: allowing only numbers and decimal point,but i have no idea to avoid pasting into a textbox prevention

However users can still paste invalid text into it. What is the best way to stop this??

onkeypress="return isNumberKey(this,event);"
function isNumberKey(obj,evt) { 
     var charCode = (evt.charCode) ? evt.which : event.keyCode
     if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 46) 
        if (window.event) //IE
        {
        window.event.returnValue = false;
        }
        else //Firefox
        {
        return false; // <-- What should I write here instead
        }
     else { 
     var input = obj.value;//alert(input);
     var len = obj.value.length; //  alert(len);
     var index = obj.value.indexOf('.'); // alert(index);
         if (index > 0 && charCode == 46) { 
            if (window.event)
            {
            window.event.returnValue = false;
            }
        else
        {
        return false;
        }
     } 
     if (index >0 || index==0) { 
         var CharAfterdot = (len + 1) - index;  
         if (CharAfterdot > 2) { 
            if (window.event)
            {
            window.event.returnValue = false;
            }
            else    
            {
            return false;
            }
         } 
    }
    if (charCode == 46 && input.split('.').length >1) {
    if (window.event) 
        {
        window.event.returnValue = false;
        }
        else
        {
        return false; 
        }
    }`enter code here`

     } 
     return true; 
  } 
raina77ow
  • 103,633
  • 15
  • 192
  • 229
Monica
  • 607
  • 4
  • 12
  • 31
  • If you're among the luckiest ones who don't have to support IE8-, bite the bullet and use `oninput` instead. – raina77ow Sep 30 '13 at 09:56
  • http://stackoverflow.com/questions/1226574/disable-copy-paste-into-html-form-using-javascript – kasper Taeymans Sep 30 '13 at 09:57
  • ... and if you're not, use [this shim](http://benalpert.com/2013/06/18/a-near-perfect-oninput-shim-for-ie-8-and-9.html) and still validate `oninput`. ) – raina77ow Sep 30 '13 at 09:58

0 Answers0