Hussian Shaik
Hussian Shaik

Reputation: 2659

how to change the phone number format in Textinput using react-native

i want the phone number(work Phone) format to be as shown in the below image, using react-native,can any one help how to work out it,any help much appreciated enter image description here

Upvotes: 6

Views: 17835

Answers (2)

C. Louis S.
C. Louis S.

Reputation: 364

This is a slightly more involved solution, but it:

  1. Accounts for when the user is backspacing
  2. Formats as they type (e.g. if they only have two digits, it formats as (55 or 5 digits as (555) 55, or 6 as (555) 555-)

function formatPhoneNumber (text, previousText) {
  if (!text) return text

  const deleting = previousText && previousText.length > text.length
  if (deleting) {
    return text
  }

  let cleaned = text.replace(/\D/g, '') // remove non-digit characters
  let match = null

  if (cleaned.length > 0 && cleaned.length < 2) {
    return `(${cleaned}`
  } else if (cleaned.length == 3) {
    return `(${cleaned}) `
  } else if (cleaned.length > 3 && cleaned.length < 5) {
    match = cleaned.match(/(\d{3})(\d{1,3})$/)
    if (match) {
      return `(${match[1]}) ${match[2]}`
    }
  } else if (cleaned.length == 6) {
    match = cleaned.match(/(\d{3})(\d{3})$/)
    if (match) {
      return `(${match[1]}) ${match[2]}-`
    }
  } else if (cleaned.length > 6) {
    match = cleaned.match(/(\d{3})(\d{3})(\d{4})$/)
    if (match) {
      return `(${match[1]}) ${match[2]}-${match[3]}`
    }
  }

  return text
}

Upvotes: 2

Nathan Corbin
Nathan Corbin

Reputation: 231

You can achieve this with regular expressions... This will format like (555) 222-9999

onTextChange(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('');

        this.setState({
            phoneNum: number
        });

        return;
    }

    this.setState({
        phoneNum: text
    });
}

Then on the <TextInput>...

<TextInput 
    onChangeText={(text) => this.onTextChange(text) }
    value={this.state.phoneNum}
    textContentType='telephoneNumber' 
    dataDetectorTypes='phoneNumber' 
    keyboardType='phone-pad' 
    maxLength={14}
/>

Upvotes: 12

Related Questions