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

【使用自定义键盘】
image.png

@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%')
  }
}

参考:https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs-V...

【使用原生键盘】

image.png

打印

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%')
  }
}

zhongcx
1 声望3 粉丝