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
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)'>