quickkninja
quickkninja

Reputation: 211

How to format textinput as phone number using react-native

When the user types their phone number, I want the number to show in a phone number format like (123) 456-7890

I'm not sure how to go about it, but this is the code I currently have.

Using UseState:

const [PNumber,setPNumber] = useState();

In My TextInput:

<TextInput
  style={Fonts.Inp}
  keyboardType={'number-pad'}
  placeholder="(604) 333-3333"
  placeholderTextColor='gray'
  maxLength={10}
  onChangeText = {(Text)=> setPNumber(Text)}
/>

So currently, it displays as '1234567890'. I would like it to show as (123) 456-7890

Upvotes: 4

Views: 5437

Answers (2)

Ganesh Moorthy A
Ganesh Moorthy A

Reputation: 204

  const phoneFormat = (phNumber) => {

    var match = phNumber.match(/(\d{3})(\d{3})(\d{4})$/)

    if (match) {

      number = ['(', match[1], ') ', match[2], '-', match[3]].join('');

      setPhNumber(number);

      return;
    }

    setPhNumber(text);
  }

...

<TextInput       
     ....
     onChangeText={phNumber => phoneFormat(phNumber)}
 />

Upvotes: 1

Jebin Benny
Jebin Benny

Reputation: 951

Try this,

_onChangeText = (text) => {
  let formatedNo = this.formatMobileNumber(text);
  this.setState({ phone: formatedNo });
};

formatMobileNumber=(text=> {
  var cleaned = ("" + text).replace(/\D/g, "");
  var match = cleaned.match(/^(1|)?(\d{3})(\d{3})(\d{4})$/);
  if (match) {
    var intlCode = match[1] ? "+1 " : "",
      number = [intlCode, "(", match[2], ") ", match[3], "-", match[4]].join(
        ""
      );
    return number;
  }
  return text;
}

...
<TextInput       
    maxLength={maxLength}
    keyboardType={keyboardType}
    onChangeText={text => {
       this._onChangeText(text);
    }}
    placeholder={placeholder}
    placeholderTextColor={Constants.APP_TEXT_GRAY_COLOR}
    value={value}
 />
...

Upvotes: 5

Related Questions