0

The code below works fine, but I would like to Supplement it by checking for a plus sign at the beginning of the line. That is, if the user adds «+», then the number becomes «+9 (999) 999-99-99», if he does not add a plus and just enters numbers, then «9 (999) 999-99-99». That is, the digits must be 11 in any case, and the «+» sign is possible only at the beginning of the line.

 var phoneInput = document.querySelector(".i_phone");
phoneInput.addEventListener("keydown", function(e) {
  "ArrowLeft" != e.key && "ArrowRight" != e.key && "Backspace" != e.key && "Delete" != e.key && "Tab" != e.key && e.preventDefault();
  var t = "1 (111) 111-11-11";
  if (/[0-9\+\ \-\(\)]/.test(e.key)) {
    var a = this.value,
      n = a.length;
    if (/[0-9]/.test(e.key))
      if ("1" == t[n]) this.value = a + e.key;
      else
        for (var r = n; r < t.length; r++) {
          if ("1" == t[r]) {
            this.value = a + e.key;
            break
          }
          a += t[r]
        }
  }
});
<input type="tel" name="phone" placeholder="Your Phone" class="i_phone" required="">
Mustofa Rizwan
  • 10,215
  • 2
  • 28
  • 43
herej76867
  • 13
  • 1

1 Answers1

0

Your regex is ok, and complies with your jquery solution. I have just filter that with an if condition at the beginning to prevent multiple + after first character. And at the end if + not being provided then added it.

var phoneInput = document.querySelector(".i_phone");
phoneInput.addEventListener("keydown", function(e) {
  "ArrowLeft" != e.key && "ArrowRight" != e.key && "Backspace" != e.key && "Delete" != e.key && "Tab" != e.key && e.preventDefault();
  var t = "+1 (111) 111-11-11";
  if (/[0-9\+\ \-\(\)]/.test(e.key)) {
    var a = this.value,
      n = a.length;
     if(n>0 && e.key=='+');
     
    else if (/[0-9+]/.test(e.key)){
      if ("1" == t[n]) 
        this.value = a + e.key;
      else if ("+" == t[n]) 
        {
            this.value = a + e.key;      
        }
      else if ("+" != t[n]) 
      {
      
          for (var r = n; r < t.length; r++) {
            if ("1" == t[r]) {
              this.value = a + e.key;
              break
            }
            a += t[r]
          }
       }
       
      if(this.value.length==1 && this.value!="+")
      {
        this.value="+"+this.value;
      
      
      }
    }   
  }
});
<input type="tel" name="phone" placeholder="Your Phone" class="i_phone" required="">
Mustofa Rizwan
  • 10,215
  • 2
  • 28
  • 43