我需要为数字输入编写验证
接受的号码:
0,21
0
0.3
78,21
8934
不允许:
00
0323
-1
021
尝试模式^(?:0,dd?|[1-9]d*(?:,dd?)?|0|)$
说明:
^
-匹配字符串的开头
(?:...)
-非捕获组
0,dd?
-从字面上匹配0,
,然后匹配一个或两个数字
|
-交替(右侧匹配图案或左侧匹配图案(
[1-9]d*(?:,dd?)?
-匹配非零数字[1-9]
,然后匹配零个或多个数字d*
,然后可选(由于末尾有?
运算符(,dd?
,所以逗号后面跟着一个或两个数字
0
-匹配0
字面上的
(?:...|)
-交替中的最后一个选项与空字符串匹配
$
-匹配字符串末尾
var myArray = ['0,21', '78,21', '8934', '', '00', '0,323', '-1', '021', '0,3', '1,3', '0'];
for(var i of myArray)
console.log(`${i} matches: ${/^(?:0,dd?|[1-9]d*(?:,dd?)?|0|)$/.test(i)}`);
这里有一个比regex 更具扩展性的方法
const okNum = ["0,21","78,21","8934",""]
const notOk = ["00","0,323","-1","021"]
const validNum = str => {
if (str.trim() === "") { console.log(str,"empty ok, passed"); return true; }
const num = str.replace(",",".")
let testNum = parseFloat(num)
if (testNum<0) { console.log(str,"negative, failed"); return false; }
if (testNum.toString().includes(".")) {
testNum = +testNum.toFixed(2)
}
else {
if (testNum.toString() !== str) { console.log(str,"not same length, failed"); return false }
}
console.log(+num,testNum,+num === testNum?"passed":"failed")
return +num === testNum
};
okNum.map(num => validNum(num))
notOk.map(num => validNum(num))