HarmonyOS TextInput处理电话号码格式

文本输入需要将电话号码xxxxxxxxxxx在输入时转为xxx xxxx xxxx的格式,采用官方api文档示例不生效,想了解还有什么需要设置的地方?

@State phoneText: string = ''

TextInput({ placeholder: $r('app.string.input_phone_hint'), text: `${this.phoneText}` })
  .onChange((number: string) => {
    this.phoneText = this.loginViewModel.formatPhoneInput(number)
  })
  .cancelButton({
    icon: {
      src: $r('app.media.icon_iv_data_delete'),
      size: 18
    }
  })
  .backgroundColor(Color.Transparent)
  .fontSize(18)
  .type(InputType.Number)
  .fontColor($r('app.color.cgws_color_FF333333_FFD1D1D1'))
  .placeholderColor($r('app.color.cgws_color_FFC2C2C2_FF5C5C5C_1'))
  .maxLength(this.loginViewModel.PHONE_NUM_TEXT_MAXSIZE_LENGTH)

public formatPhoneInput(number: string): string {
  let phoneText = ''
  let phoneNumberNoSpace: string = this.removeSpace(number);
  if (phoneNumberNoSpace.length > this.PHONE_NUM_TEXT_MAXSIZE_LENGTH - 2) {
    phoneText = phoneNumberNoSpace;
  } else if (this.checkNeedNumberSpace(number)) {
    if (phoneNumberNoSpace.length <= 3) {
      phoneText = phoneNumberNoSpace;
    } else {
      let split1: string = phoneNumberNoSpace.substring(0, 3);
      let split2: string = phoneNumberNoSpace.substring(3);
      phoneText = split1 + ' ' + split2;
      if (phoneNumberNoSpace.length > 7) {
        split2 = phoneNumberNoSpace.substring(3, 7);
        let split3: string = phoneNumberNoSpace.substring(7);
        phoneText = split1 + ' ' + split2 + ' ' + split3;
      }
    }
  } else {
    phoneText = number;
  }
  return phoneText
}

checkNeedNumberSpace(numText: string) {
  let isSpace: RegExp = new RegExp('[\\+;,#\\*]', 'g');
  let isRule: RegExp = new RegExp('^\\+.*');

  if (isSpace.test(numText)) {
    // 如果电话号码里有特殊字符,就不加空格
    if (isRule.test(numText)) {
      return true;
    } else {
      return false;
    }
  }
  return true;
}

removeSpace(str: string): string {
  if (StrUtil.isEmpty(str)) {
    return ''
  }
  return str.replace(new RegExp("[\\s]", "g"), '')
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
HarmonyOS
2024-12-25 07:47:09
659浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
Excelsior_abit

因为设置的InputType为Number类型,这是一个纯数字键盘,会自动过滤掉空格,所以不会有手机号格式化后 的效果,把InputType设置为normal类型时,即可

可以通过设置.inputFilter("[0-9]| ")过滤,只允许输入数字和空格

分享
微博
QQ
微信
回复
2024-12-25 10:56:54
相关问题
如何对电话号码进行格式
1426浏览 • 1回复 待解决
如何获取电话号码归属地
1025浏览 • 1回复 待解决
HarmonyOS 拨打电话功能
796浏览 • 1回复 待解决
HarmonyOS 如何调用拨打电话界面
1141浏览 • 1回复 待解决
HarmonyOS 无法跳转电话拨号页面
839浏览 • 1回复 待解决
HarmonyOS 拨打电话系统能力
1613浏览 • 1回复 待解决