繁体   English   中英

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

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

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

function isNumericKey(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; }
        return true;
    }
    function submitMyNumber()
    {
        var input = document.getElementById('myInput').value;
        return 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}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM