Home > Back-end >  libphonenumber-js validate on input
libphonenumber-js validate on input

Time:10-06

I'm using this library to format the phone input like this
input: xxxxxxxxxxx
formatter returns: xxxx xxx xx xx

What i want and is not avaliable in the documentation is to prevent writing in the input when the phone number is full.

Example: the number above is 9 charecter length, i don't need the user to be able to write more than that

Code to format input:

telInput.addEventListener('input', function () {
    const formatter = new AsYouType(isoCode2)
    telInput.value = formatter.input(telInput.value)
})

Note: the phone number lenght is changeable based on another select

CodePudding user response:

you can dynamically prevent user from typing in keypress. sth like this:

telInput.addEventListener('keypress', function (e) {
    if(telInput.value.length>maxLength){
    e.preventDefault()
    }
})

CodePudding user response:

I could fix it by setting a new maxlength when ever the phone is changes(idea by avva)

const template = formatter.formatter.template || 'xxxxxxxxxx'
const newLength = template.length.toString()
telInput.setAttribute('maxlength', newLength)
  • Related