I'm trying to format a html text input box so that it only accepts numeric values (using javascript). This means the input can only be a digit, a minus or a dot/comma (a comma gets replaced with a dot anyway).
The thing is, a minus must be prevented if it is not the first character of the string. Ex: "-30" is a valid input, but "80----20" is not. Does anyone has any idea on how to solve this?
var div = document.getElementById("div");
function inputHandle(event, object){
var input = document.getElementById("value");
var comma = false;
for (i=0; i<input.value.length; i++) {
var array = input.value;
if (input.value[i] == ".") {
comma = true;
}
}
if ((event.keyCode == 13) && (Number(input.value) < Number.MAX_SAFE_INTEGER)) {
object.innerHTML = Number(input.value);
}
if ((event.charCode == 44) && (comma == false)) {
input.value = input.value + ".";
event.preventDefault();
}
if (!((/^-?\d*\.?\d*$/.test(event.key) == true)
|| (((event.charCode == 118) || (event.charCode == 99) || (event.charCode == 97)) && (event.ctrlKey))
|| (event.keyCode == 8)
|| (event.keyCode == 46)
|| (event.keyCode >= 35 && event.keyCode <= 40)
)) {
event.preventDefault();
}
if ((event.charCode == 46) && (comma == true)) {
event.preventDefault();
}
}
<div id="div"></div>
<input type='text' onkeypress='inputHandle(event, div)' accept-charset='ISO-8859-1' id='value' name='coefficientvalue' placeholder='Enter a value...'>