【HarmonyOS】鸿蒙TextInput小数限制

【HarmonyOS】TextInput设置最多两位小数且整数部分不超过6位方法

【使用自定义键盘】

@Entry
@Component
struct Page47 {
  controller: TextInputController = new TextInputController();
  @State inputValue: string = '';

  // 自定义键盘组件
  @Builder
  CustomKeyboardBuilder() {
    Column() {
      Button('x')
        .onClick(() => {
          // 关闭自定义键盘
          this.controller.stopEditing();
        })
      Grid() {
        ForEach([1, 2, 3, 4, 5, 6, 7, 8, 9, '.', 0, '删除'], (item: number | string) => {
          GridItem() {
            Button(item + '')
              .width(110)
              .onClick(() => {
                if (item == '删除') {
                  this.inputValue = this.inputValue.substring(0, this.inputValue.length - 1);
                  return;
                }
                this.inputValue += item;
                let regex = /^-?\d{0,6}(?:\.\d{0,2})?$/
                let test = regex.test(this.inputValue)
                console.info(`onChange regex.test(this.inputValue) :${test}`)
                if (!test) {
                  this.inputValue = this.inputValue.substring(0, this.inputValue.length - 1);
                }
              })
          }
        })
      }
      .maxCount(3)
      .columnsGap(10)
      .rowsGap(10)
      .padding(5)
    }
    .backgroundColor(Color.Gray)
  }

  build() {
    Column() {
      TextInput({
        text: $$this.inputValue, placeholder: '请输入内容', controller: this.controller
      })
        .customKeyboard(this.CustomKeyboardBuilder())
    }
    .height('100%')
    .width('100%')
  }
}

参考:文档中心

【使用原生键盘】

打印

0.1 --> true
.1 --> true
1. --> true
1.0 --> true
0.1 --> 0.1
.1 --> 0.1
1. --> 1
1.0 --> 1

代码

@Entry
@Component
struct Page47 {
  @State inputValue: string = '';
  regex = /^-?\d{0,6}(?:\.\d{0,2})?$/

  build() {
    Column() {
      Button('正则测试').onClick(() => {

        console.info(`0.1 --> ${this.regex.test('0.1')}`)
        console.info(`.1 --> ${this.regex.test('.1')}`)
        console.info(`1. --> ${this.regex.test('1.')}`)
        console.info(`1.0 --> ${this.regex.test('1.0')}`)

        console.info(`0.1 --> ${0.1}`)
        console.info(`.1 --> ${.1}`)
        console.info(`1. --> ${1.}`)
        console.info(`1.0 --> ${1.0}`)
      })
      TextInput({
        text: $$this.inputValue,
        placeholder: '请输入内容'
      })
        .onChange((value: string) => {
          console.info(`onChange inputValue start :${this.inputValue}`)
          let test = this.regex.test(this.inputValue)
          console.info(`onChange regex.test(this.inputValue) :${test}`)
          if (!test) {
            this.inputValue = this.inputValue.substring(0, this.inputValue.length - 1);
          }
        })
    }
    .height('100%')
    .width('100%')
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值