我正在尝试实现用于验证负数的正则表达式。这是我的尝试。
html
<input type="number" id="inC" />
<div id="outC">
</div>
js
debugger;
const failedInput = document.getElementById("inC");
const textOut = document.getElementById("outC");
failedInput.addEventListener("input", function(e) {
const ct = e.currentTarget;
textOut.innerText = ct.value;
if (/^((\-(\d*))$/.test(ct.value)) {
} else {
ct.value = "";
}
});
我希望输入会删除除负数以外的所有内容。但是出于某些原因,也允许使用正数。我在这里想念什么?
我希望我的输入仅接受负整数(最好不包含零)。
您在正则表达式中缺少结尾括号。您的样本最初给出了错误:
语法错误:括号未结束
您的正则表达式:
/^((\-(\d*))$/
那是三个开场括号,两个闭行括号。
它应该是:
/^(\-(\d*))$/
看一下:添加了结束括号,它现在可以按预期运行。
if (/^(\-(\d*))$/.test(ct.value)) {
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句