jackocnr / intl-tel-input

A JavaScript plugin for entering and validating international telephone numbers
https://intl-tel-input.com
MIT License
7.54k stars 1.94k forks source link

Force to use the prefix #1566

Closed Magic73 closed 4 months ago

Magic73 commented 4 months ago

Hi, I would like to force the user to enter a number so that the prefix is always there. currently, even if I set it to default, he has the possibility of deleting it and entering a number without the prefix. Is it possible to prevent it from deleting it, or to reinsert it automatically when it loses focus and control?

Thank you :)

jackocnr commented 4 months ago

Can I ask why you want this?

Did you know that even if the user types their number in the national format (without the international dial code), you can always use getNumber to get the full international number (including the international dial code)?

Magic73 commented 4 months ago

HI, to add validation on the obligatory nature of having a prefix without having to use other tools afterwards, such as pop-ups or external alerts. Some of our users, when editing the telephone number, have the habit of removing the prefix with the result that the subsequent sending of a text message fails due to the lack of it.

By having an integrated validation check that requires the presence of the prefix, we standardize the input error reporting.

jackocnr commented 4 months ago

As per my previous message, you do not need to restrict the user in this way. You can allow the user to enter their number however they like, and you can always get the standardised international number using getNumber. Closing for now, but let me know if you have any problems.

Magic73 commented 4 months ago

image

calling getNumber on this, doesn't return +41 12345678

image

Edit ----------

I just solved in this way:

  input.onblur = function () {
      if (input.value) {
          const countryData = iti.getSelectedCountryData();
          iti.setCountry(countryData.iso2);
          const number = iti.getNumber();

          input.value = number;
          iti.setNumber(number);

          var event = new Event('change');
          input.dispatchEvent(event); // Notify Blazor about the change
      }
  }
jackocnr commented 4 months ago

calling getNumber on this, doesn't return +41 12345678

No because that's not a valid number. As per the readme, getNumber only works with valid numbers so you need to use isValidNumber to confirm the number is valid first. If it is valid, then you can use getNumber to get the full international number.