Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Prevent user from typing more than a single decimal, and prevent user from typing more than 2 numbers after decimal

I’ve currently got this JS code attached that validates for numbers and dots in an input, but I want to also prevent user from typing in more than one dot for decimal, and not more than two other numbers after the dot.

How can I do this?

Thank you

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

function validate(evt) {
    var theEvent = evt || window.event;
    // Handle paste
    if (theEvent.type === 'paste') {
        key = event.clipboardData.getData('text/plain');
    } else {
    // Handle key press
        var key = theEvent.keyCode || theEvent.which;
        key = String.fromCharCode(key);
    }
    var regex = /[0-9]|\./;
    if( !regex.test(key) ) {
      theEvent.returnValue = false;
      if(theEvent.preventDefault) theEvent.preventDefault();
    }
  }
        <input placeholder="Enter amount..." maxlength="5" onkeypress='validate(event)'>

>Solution :

function validate(evt) {
  var theEvent = evt || window.event;
  var inputField = theEvent.target || theEvent.srcElement;

  // prevent user pasting in values
  if (theEvent.type === 'paste') {
    key = event.clipboardData.getData('text/plain');
  } else {
    var key = theEvent.keyCode || theEvent.which;
    key = String.fromCharCode(key);
  }

  // allow only numbers and dots
  var regex = /[0-9]|\./;
  if (!regex.test(key)) {
    theEvent.returnValue = false;
    if (theEvent.preventDefault) theEvent.preventDefault();
    return;
  }

  // check if there is already a dot
  if (key === '.' && inputField.value.includes('.')) {
    theEvent.returnValue = false;
    if (theEvent.preventDefault) theEvent.preventDefault();
    return;
  }

  // only 2 numbers after dot
  var parts = inputField.value.split('.');
  if (parts.length === 2 && parts[1].length >= 2 && key !== '.') {
    theEvent.returnValue = false;
    if (theEvent.preventDefault) theEvent.preventDefault();
  }
}
<input placeholder="Enter amount..." maxlength="5" onkeypress='validate(event)'>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading