运行代码时,文本框不接受任何键值。如果我只使用/ \ d /它工作并只接受数字。我怎样才能使这个日期工作?
<html>
<head>
</head>
<body>
<script type="text/javascript"></script>
<form method="post" action="javascript:alert('Form submitted!')" id="myForm">
<div>
<label>Type a phone number:</label><br>
<input type="text" id="birthday" name="yourBirthday" value="">
</div>
</form>
<script type="text/javascript">
(function () {
var birthday = document.getElementById("birthday");
birthday.addEventListener("keypress", function (event) {
var characterEntered = event.charCode;
if (!/\d{2}[./-]\d{2}[./-]\d{4}/.test(String.fromCharCode(characterEntered))) {
event.preventDefault()
}
}, false)
})();
</script>
</body>
</html>
答案 0 :(得分:1)
问题是event.charCode;
是一个字符。我想你想要阻止像数字或超级的字符。所以正确的正则表达式是\d|[-]
,这意味着数字或超级
检查JSFiddle的工作示例:http://jsfiddle.net/m629pL3n/