<script>
$(function () {
$("#my").keyup(function (e) {
var $currentTarget = $(e.currentTarget);
e.currentTarget.value= e.currentTarget.value.replace(/[^0-9\/]/g,'');
var value2 = $currentTarget.val().replace('/', '');
if (value2 != null && value2.length == 2 && $currentTarget.val().indexOf("/") == -1) {
$currentTarget.val($currentTarget.val() + "/");
} else if (value2 == "") {
$currentTarget.val('');
}
});
$("#my").keydown(function (e) {
var caretPosition = $(e.currentTarget)[0].selectionStart;
console.log("光标位置:", caretPosition);
if (e.which != 8 && e.which != 37 && e.which != 39 && e.which != 46) {
var regex = /^[0-9]+$/;
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (!regex.test(str)) {
e.preventDefault();
}
// var regex = /^[0][1-9]|[1][0-2]\/[0-9]{2}$/;
if (caretPosition == 2 || $(e.currentTarget).val().length == 5) {
e.preventDefault();
}
}
});
});
</script>
输入类似MM/YY类型的字符串
于 2024-09-04 00:31:01 首次发布