一、背景:
想要實現一功能:
1. 最多只能輸入兩位小數,類似的價格限制
2. 實時監聽限制輸入,禁止輸入不符合規范的字符(當輸入違禁字符,進行刪除操作)
這樣做的優點:
1. 在用戶輸入時直接進行限制,而不是在輸入完才進行檢測提示 --> 實時性
2. 直接在輸入時進行規范,用戶體驗更好
二、分析:
1. 實現對輸入數據的實時監控
web一般使用 onkeyup、onpaste、oncontextmenu等事件來實時監聽輸入的字符變化
具體請看這篇博客: input實時監聽控制輸入框的輸入內容和長度,並進行提示和反饋
react-native使用的TextInput,它自帶的onChangeText的方法可以實現實時監聽輸入變化
2. 需要使用正則表達式來實現字符的檢測和替換
檢測是否是保留兩位小數的字符格式(只能放在blur事件和react-native的TextInput的onEndEditing內使用,進行數據檢測)
reg = (([1-9]{1}\d*)|(0{1}))(\.\d{0,2})或者 /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/
三、正文
newText = newText.replace(/^0+[0-9]+/g, "0"); //不能以0開頭輸入
newText = newText.replace(/[^\d.]/g,""); //清除"數字"和"."以外的字符
newText = newText.replace(/^\./g,""); //驗證第一個字符是數字(即第一個字符非“.”)
newText = newText.replace(/\.{2,}/g,"."); //只保留第一個, 清除多余的
newText = newText.replace(".","$#$").replace(/\./g,"").replace("$#$","."); newText = newText.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3'); //只能輸入兩個小數
//React-Native中的使用
onChangeText={(text) => { let newText = (text != '' && text.substr(0,1) == '.') ? '' : text;
newText = newText.replace(/^0+[0-9]+/g, "0"); //不能以0開頭輸入 newText = newText.replace(/[^\d.]/g,""); //清除"數字"和"."以外的字符
newText = newText.replace(/\.{2,}/g,"."); //只保留第一個, 清除多余的
newText = newText.replace(".","$#$").replace(/\./g,"").replace("$#$","."); newText = newText.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3'); //只能輸入兩個小數
this.setState({price: newText}) } }
四、結語:
結束!