react native中TextInput作为数字框使用

1.控件设置键盘为数字键盘(但是这控制不住,用户可以切换键盘)

<TextInput keyboardType='numeric'
     placeholder={'请输入'}
     underlineColorAndroid='transparent'
     style={styles.labelNumText}
     onChangeText={(text) => {
          specialReportDataDetail.ticketPrice = formatPositiveNum(text, 2, 100000);
          this.updateReportDetail(specialReportDataDetail);
     }}
     value={specialReportDataDetail.ticketPrice ? specialReportDataDetail.ticketPrice.toString() : ''}
/>

2.关键是输入内容校验

//格式化正数
// text:要格式化的文本
// decimalLength:小数位数
// max:转换为数字后最大值的限制
export function formatPositiveNum(text,decimalLength,max){
  if(decimalLength==null||decimalLength<0){
    ToastShort('小数位数不能小于0')
    return;
  }
  if(decimalLength===0){
    text = text.replace(/[^0-9]/g, '');
  }else{
    text = text.replace(/[^\.0-9]+/, '');
    if(text!=null){
      let dotArr = text.match(/\./g)
      if(dotArr!=null&&dotArr.length>1){
        text = text.replace(/.$/, '')
      }
      if(dotArr!=null&&dotArr.length===1){
        let decimal = text.split('.')
        if(decimal[1].length>decimalLength){
          text = text.replace(/.$/, '')
        }
      }
    }
  }
  if(max!==null&&text>max){
    text = text.replace(/.$/, '')
  }
  return text;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值