Lazloman
Lazloman

Reputation: 1347

How to limit a form filed to accept only numbers while allowing pasting into the field

I need to have a form field accept only numbers, while allowing the user to paste into the same field. I found this js script that only allows numbers, but you can't paste numbers:

function isNumber(event) {
  if (event) {
    var charCode = (event.which) ? event.which : event.keyCode;
    if (charCode != 190 && charCode > 31 && 
       (charCode < 48 || charCode > 57) && 
       (charCode < 96 || charCode > 105) && 
       (charCode < 37 || charCode > 40) && 
        charCode != 110 && charCode != 8 && charCode != 46 )
       return false;
  }
  return true;
}

I've looked for angularjs solutions, but they suffer from the same "no pasting" issue. One would think angularjs has a built-in filter for this, but alas, no joy. SO can someone point me to some code or give me pointers to writing a filter that does this? Thanks

Upvotes: 0

Views: 281

Answers (1)

BenCr
BenCr

Reputation: 6052

Can you use HTML 5 <input type="number" />

If you need to perhaps include Modernizr.

http://modernizr.com/docs/#features-html5

Upvotes: 1

Related Questions