Ask for answers from regular people.

the requirement is like this. The input input box can only enter numbers and decimals, the beginning cannot be a dot and zero, and the decimal can only be two digits at most. Thank you!

Mar.11,2021

/ ^ d * (?: .d {0 2})? $/
reference article: http://www.jb51.net/article/8.


<input id="input">
var reg = /^[1-9]\d*(\.\d{0,2})?$|^0(\.\d{0,2})?$|^-([1-9]{1}\d*(\.\d{0,2})?)?$|^-(0(\.\d{0,2})?)?$/;

var input = document.getElementById('input');

var oldValue = '';
input.addEventListener('input',function(){
  console.log(input.value)
    if(input.value && !reg.test(input.value)){
      input.value = oldValue;
    }  
  oldValue = input.value;
});

input.addEventListener('change',function(){
   if(input.value.endsWith('.') || input.value.endsWith('-')){
     input.value = input.value.slice(0,-1);
   }
});

https://codepen.io/randyou/pe.

Menu