Skip to content

Instantly share code, notes, and snippets.

@jukbot
Created August 1, 2024 17:23
Show Gist options
  • Select an option

  • Save jukbot/46ddde54d44e41d9764838ff37d72284 to your computer and use it in GitHub Desktop.

Select an option

Save jukbot/46ddde54d44e41d9764838ff37d72284 to your computer and use it in GitHub Desktop.

Revisions

  1. jukbot created this gist Aug 1, 2024.
    29 changes: 29 additions & 0 deletions validate.js
    Original 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()
    }
    }