There is a regular expression that gives input only numbers from 0 to 9 /[^0-9]/g .

It is necessary that the input be any numbers, except for 0, that is, 10.20 - it is possible, just one - it is impossible.

Tell me, please, which way to look, to do this?

  • At what point does the check occur when the keydown event occurs? Or at a form? - Aleksander K.
  • happens on keydown - ennet

5 answers 5

If keypress processing keypress :

 var field = document.getElementById('field'); field.addEventListener('keypress', function(e) { var char = String.fromCharCode(e.which), valLen = field.value.length; if (char !== '' & !char.match(/[0-9]/) || char === '0' & valLen === 0) { e.preventDefault(); return false; } }); 
 <input type="text" id="field" /> 

  • Delete the character, move the cursor is also impossible;) - Visman
  • Does not work. Enter 10 , move the cursor to the left, delete 1 , remains 0 . - Qwertiy
  • @Qwertiy. How do you delete and move the cursor works? In FF40, only numbers can be dialed, even Tab does not move the cursor to another element. - Visman Sep.
  • @Visman, yes. Yandex browser 43.0.2357.2877 x32. - Qwertiy
  • Yes you are right. Sorry, fixed the example. - Aleksander K.

Apparently, you need somewhere such an expression

 /^[1-9][0-9]*$/ 

    Solution only by means of html

     <input type="text" pattern="[1-9]\d*" required placeholder="Введите число > 0" /> <input type="text" placeholder="Введите текст" /> 

    • Your regular season prohibits negative numbers - AntonioK
    • @AntonioK, the author of the question is only talking about numbers, that is, positive numbers. Look at all 4 answers and find at least in one sign - . - Visman Sep.

    Any positive integer without leading zeros:

     ^[1-9]\d*$ 

      If you want to allow leading zeros, then:

       /^(?!0*$)\d*$/