如何向正则表达式添加特殊符号以允许在文本字段中使用

How to add special symbol to the regular expression to allow in text field?

本文关键字:文本 字段 正则表达式 添加 特殊符号      更新时间:2023-09-26

我有以下代码,它只允许数字0-9。
但我也想允许-(hyphon)。[- ASCII 代码为 45]
我试过了..但是没有用..你能更新我的代码吗?

函数是数字键(e)        {        if (window.event) { var charCode = window.event.keyCode; }        else if (e) { var charCode = e.which; }        else { return true; }        if (charCode> 31 && (charCode <48 || charCode> 57)) { return false; }        返回真;    }    函数提交我的号码()    {        var input = document.getElementById('myInput').value;        返回 input.match(/^[0-9-]+$/) != null;    }
 <form>
<input type="text" id="myInput" name="myInput" onkeypress="return isNumericKey(event);" /><br />
    <input type="submit" id="mySubmit" name="mySubmit" value="Submit My Number" onclick="return submitMyNumber();" />
</form></pre>
 

拉克斯曼·乔达里

似乎您过滤了 45 个字符

 function isNumericKey(e)
        {
        if (window.event) { var charCode = window.event.keyCode; }
        else if (e) { var charCode = e.which; }
        else { return true; }
        if (charCode == 45 || (charCode >= 48 && charCode <= 57)
           return true;
        else
           return false;
    }

会更好地工作。

正则表达式中指定范围时,以连字符开头。

 /^[-0-9]+$/
    ^-- here
 /^[0-9-]+$/
       ^--- does not work here 

如果要匹配日期,则模式可能类似于dd-dd-dd(但是哪种格式?ISO YYYY-MM-DD ?或其他东西)更正确的模式将是。

 /^'d{4}-'d{2}-'d{2}$/

可能这个更好

 /^[12]'d{3}-[01]'d-[0-3]'d$/

对于 DD-MM-YYYY 恢复模式非常简单:

 /^[0-3]'d-[01]'d-[12]'d{3}$/

> 如果您想接受 29-06-2012 即 2 位数字连字符 2 位数字连字符 4 位数字,这是日期模式,正则表达式[0-9]{2}-[0-9]{2}-[0-9]{4}