Skip to content

Instantly share code, notes, and snippets.

@jukbot
Created August 1, 2024 17:23
Show Gist options
  • Save jukbot/46ddde54d44e41d9764838ff37d72284 to your computer and use it in GitHub Desktop.
Save jukbot/46ddde54d44e41d9764838ff37d72284 to your computer and use it in GitHub Desktop.
Validate input number to allow only numeric, 1 decimal and max to 3 decimal places
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()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment