Skip to content

Instantly share code, notes, and snippets.

@dengsauve
Last active September 30, 2020 00:43
Show Gist options
  • Save dengsauve/8f1cb2d3e567b9939b06544aa97c21b0 to your computer and use it in GitHub Desktop.
Save dengsauve/8f1cb2d3e567b9939b06544aa97c21b0 to your computer and use it in GitHub Desktop.
Realtime number input validation (playing a little code golf)
document.getElementById("numberInput").addEventListener("input", function (e) {
const numberArr = e.target.value.toString().split("."); // float as string, two values
if (numberArr.length > 1 && numberArr[1].length > 2) // checking 2nd value longer than 2, then assigning..
e.target.value = parseFloat(numberArr[0] + "." + numberArr[1].substring(0,2)); // ..the correct value
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment