【问题标题】:Allow only numbers and forward slash in a HTML text box在 HTML 文本框中只允许数字和正斜杠
【发布时间】:2020-03-11 09:30:55
【问题描述】:

我想要一个日期格式的文本。我能够设法获得像 20/03/2020 但它也接受字符

如果我使用 /[^0-9]/gi,则按下时会立即删除章程,但正斜杠也会被删除(我需要正斜杠)。 如果我使用 /[^0-9][//]/gi 那么我会得到正斜杠,但它不限制字符。

如何解决

function restrictAlphas(e) {

            var invalidcharacters = /[^0-9][/\/]/gi;


            var xval = document.getElementById("idcrd").value;
            var length = xval.length;


            if (length<=10){
                if (invalidcharacters.test(xval)) {
                    newVal= xval.replace(invalidcharacters, "");
                    document.getElementById("idcrd").value = newVal;

                }
                else {
                    if ((length == 2 || length == 5)) {

                        document.getElementById("idcrd").value = xval + '/';
                    }
                }
        }




        }

HTML:

 <input type ="text"  name="crd" id="idcrd" maxlength="10" onkeyup="return restrictAlphas(event)"  />

【问题讨论】:

  • 使用 HTML 提供的 date input (&lt;input type="date" /&gt;) 可能会好得多。
  • 为什么不使用输入类型日期?
  • &lt;input type="date" /&gt; 会解决你的问题。
  • 我使用的是 HTML 和 IE 11,所以 不起作用

标签: javascript html regex


【解决方案1】:

function restrictAlphas(e) {
     e.target.value = e.target.value.replace(/[\D]/g, '').replace(/(\d{2})/, "$1/").replace(/(\d{2}\/\d{2})/, "$1/");
}
 &lt;input type ="text"  name="crd" id="idcrd" maxlength="10" oninput="restrictAlphas(event)"  /&gt;

【讨论】:

    【解决方案2】:

    您可以使用 html5 pattern 属性。并使用[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9] 作为正则表达式模式来匹配这种情况下所需的字符。

    <form action="" method="post">
        <input type="text"  name="crd" id="idcrd" maxlength="10" pattern="[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]"  />
        <input type="submit" value="Button">
    </form>

    【讨论】:

    • 再次检查您的示例。它在第一组数字/斜线之后失败。
    • 您想使用多个正斜杠吗?
    • 您不能输入日期。例如,您只能输入02/。除此之外,您的示例将失败。
    • 好的,我正在更新它
    • @Andy 你现在可以再试一次。
    猜你喜欢
    • 2017-03-24
    • 1970-01-01
    • 1970-01-01
    • 2011-07-30
    • 1970-01-01
    • 2010-10-24
    • 1970-01-01
    • 2013-04-12
    • 1970-01-01
    相关资源
    最近更新 更多