如何使用react-native更改Textinput中的电话号码格式

问题描述 投票:0回答:3

我想要电话号码(工作电话)格式如下图所示,使用react-native,任何人都可以帮助如何解决它,任何帮助非常感谢 enter image description here

react-native
3个回答
12
投票

您可以使用正则表达式来实现此目的...其格式类似于 (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
    });
}

然后在

<TextInput>
...

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

2
投票

这是一个稍微复杂一些的解决方案,但它:

  1. 考虑用户何时退格
  2. 按输入格式设置(例如,如果只有两位数字,则格式为
    (55
    或 5 位数字为
    (555) 55
    ,或 6 位数字为
    (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
}


© www.soinside.com 2019 - 2024. All rights reserved.