【发布时间】: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 (
<input type="date" />) 可能会好得多。 -
为什么不使用输入类型日期?
-
<input type="date" />会解决你的问题。 -
我使用的是 HTML 和 IE 11,所以 不起作用
标签: javascript html regex