Created
August 1, 2024 17:23
-
-
Save jukbot/46ddde54d44e41d9764838ff37d72284 to your computer and use it in GitHub Desktop.
Revisions
-
jukbot created this gist
Aug 1, 2024 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,29 @@ export function validateNumberInput (e, min = 0, max = 1e10) { const currentValue = e.target.value const validKeys = ['ArrowLeft', 'ArrowRight', 'Backspace', 'Tab', 'Delete', '.'] // Allow valid control keys if (validKeys.includes(e.key)) { return } // Prevent entering non-numeric keys except '.' if (!/^\d$/.test(e.key)) { e.preventDefault() return } const predictedString = currentValue + e.key // Check for multiple decimal points const decimalCount = (predictedString.match(/\./g) || []).length // Calculate the number of decimal places in the predicted string const decimalPlaces = predictedString.includes('.') ? predictedString.split('.')[1].length : 0 // Block if the key is 'e', 'E', '+', '-', or if decimal count is more than 1, or if decimal places are more than 3 const isBlock = ['e', 'E', '+', '-'].includes(e.key) || decimalCount > 1 || decimalPlaces > 3 // Check if the predicted value is within range and valid const predictedValue = parseFloat(predictedString) if (isBlock || isNaN(predictedValue) || predictedValue < min || predictedValue > max) { e.preventDefault() } }