简体   繁体   中英

Make an input that only allow numbers, one dot and two decimal places

There's any way to validate in javascript multiple inputs in order to just allow numbers, one dot and two optional decimal places in each of them?

EDIT: It should allow the next ones:

  • 12.65
  • 12.6
  • 12.
  • 12
  • 1

I managed to do this:

<input type="number" onkeypress="return isDecimalKey(event,this)"/>
<input type="text" onkeypress="return isDecimalKey(event,this)"/>
<input type="number" onkeypress="return isDecimalKey(event,this)"/>
<input type="text" onkeypress="return isDecimalKey(event,this)"/>
function isDecimalKey(evt, elem) {

    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode != 46 && (charCode < 48 || charCode > 57)))
        return false;
    else {
        var dot = 0;
        for (var i = 0; i < elem.value.toString().length; i++) {
            if (elem.value.toString()[i] == 46)
                dot++;
        }
        if (charCode == 46 && dot == 1)
            return false;
    }
    return true;
}

But it doesn't work well, and I'm still able to insert multiple dots and more than 2 decimals, but only accepts numbers and dots.

Try with this

HTML

<input autofocus pattern="^\d+\.{0,1}\d{0,2}$" required oninput="isDecimalKey(event,this)">

JS

const isDecimalKey = (event,element)=>{
       event.target.setCustomValidity('');
      const patt = /^\d+\.{0,1}\d{0,2}$/;
      let value = event.target.value;
      if(!patt.test(value)){
        event.target.reportValidity();
        element.setAttribute("maxlength",value.length);
      }
      else
      {
        element.removeAttribute("maxlength")
      }
     if(value.length === 0){
        element.removeAttribute("maxlength");
     }
   }

You can try:

input type="number" 
step="0.01"
onkeypress={() => { isDecimalKey(event,this) }} 

Use the following regex to validate your inptut value:

[0-9]*\.?[0-9]{2}.test('21.33') //true

[0-9]*\.?[0-9]{2}.test('3333.111') //false

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM