网页文本框限制输入的格式为1999-01-02,输入数字后 - 会自动加上
<!DOCTYPE html>
<html>
<head>
<title>限制输入格式</title>
</head>
<body>
<input type="text" id="dateInput" onkeypress="limitInput(event)" onkeyup="formatDate(event)">
<script>
function limitInput(event) {
const input = event.target;
const maxLength = 8;
if (input.value.replace(/[^0-9]/g, '').length >= maxLength && event.keyCode !== 8) {
event.preventDefault();
}
}
function formatDate(event) {
const input = event.target;
let value = input.value.replace(/[^0-9]/g, '');
if (value.length > 8) {
value = value.substr(0, 8);
}
if (value.length >= 5) {
value = value.replace(/^(\d{4})(\d{0,2})(\d{0,2})/, function(match, p1, p2, p3) {
const month = p2 ? Math.min(Math.max(parseInt(p2, 10), 1), 12).toString().padStart(2, '0') : '';
const date = p3 ? Math.min(Math.max(parseInt(p3, 10), 1), 30).toString().padStart(2, '0') : '';
return p1 + (month ? '-' + month : '') + (date ? '-' + date : '');
});
}
input.value = value;
}
</script>
</body>
</html>