T
T
Togar2022-03-06 16:09:52
JavaScript
Togar, 2022-03-06 16:09:52

How to make onChange phone number validation in React?

Tell me how to make onChange phone number validation so that it works like this:
the user gradually enters a string, and it is automatically generated as a phone number:

1111 => +1 (111)
00000000000 => +0 (000) 000 00 00

Answer the question

In order to leave comments, you need to log in

3 answer(s)
K
Kirill Makarov, 2022-03-06
@kirbi1996

Google react input mask or similar libraries

G
Gradient1712, 2022-03-07
@Gradient1712

It's worth taking a look at the Cleave.js library

S
shsv382, 2022-03-10
@shsv382

On pure JS

const phone = document.getElementById('phone');

const phoneFormat = function(e) {
  let content = e.target.value;
  if(!content) return;
  content = Array.from(content).filter(ltr => ltr.charCodeAt(0) > 47 && ltr.charCodeAt(0) < 58);
  
  switch(content[0]) {
    case "8":
      content[0] = "7";
      break;
    case "9":
      content.unshift("7");
      break;
    default:
      break;
  }
  
  let [countryCode, operatorCode, number3, number21, number22] = [
                                                                  content[0], 
                                                                  content.slice(1,4).join(''), 
                                                                  content.slice(4,7).join(''),
                                                                  content.slice(7,9).join(''),
                                                                  content.slice(9,11).join(''),
                                                                 ]

  e.target.value = countryCode.length ? `+${countryCode}` : '';
  if(operatorCode.length) e.target.value += `(${operatorCode}`;
  if(number3.length) e.target.value += `)${number3}`;
  if(number21.length) e.target.value += `-${number21}`;
  if(number22.length) e.target.value += `-${number22}`;
}

phone.oninput = (e) => phoneFormat(e);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question