Search code examples
javascriptvalidationnumbersrangepostal

Javascript limit input to specific numbers


I wanted to create an input field for a postal code check, i found number ranges to not work, as they arent all sequential:

In Dresden one postal code is 01157 but the next one is 01169, so a simple range won't do.

Is it possible to have all the necessary zip codes stored and to then compare if the input is one of these and if yes, then it will be valid?


Solution

  • So here is a minimal solution for a basic understanding of how this works in principle.

    I'm using an event listener, so whenever the input value changes, a check is done. If the provided value is included in the list of valid numbers, the input is colored green, otherwise red.

    The submit button is only enabled if a valid input was provided.

    const plzList = [1, 4, 9, 185, 2164]
    
    const plzInput = document.getElementById('plzInput')
    const submit = document.getElementById('submit')
    
    plzInput.addEventListener('input', e => {
      const plzProvided = e.target.value
      const isValid = plzList && plzList.includes(parseInt(plzProvided))
      e.target.style.backgroundColor = isValid ? 'green' : 'red'
      submit.disabled = !isValid;
    });
    <input id="plzInput" type="number" />
    <input id="submit" type="submit" disabled/>