$(function() {
//Put our input DOM element into a jQuery Object
var $jqDate = jQuery('#daterangefield');
//Bind keyup/keydown to the input
$jqDate.bind('keyup','keydown', function(e){
//To accomdate for backspacing, we detect which key was pressed - if backspace, do nothing:
if(e.which !== 8) {
var numChars = $jqDate.val().length;
if(numChars === 2 || numChars === 5 || numChars === 10 || numChars === 15 || numChars === 18){
var thisVal = $jqDate.val();
if (numChars === 10) {
thisVal += ' - ';
}else{
thisVal += '/';
}
$jqDate.val(thisVal);
}
}
});
// Validate code
$(document).ready(function(){
$("#daterangefield").keypress(function (e){
var keyx = e.which;
$("#error_msg").html("");
var key = e.keyCode || e.which;
$return = (key == 8 || key == 32 || (key >= 48 && key <= 57) || (key > 64 && key < 91) || (key > 98 && key < 123) );
if(String.fromCharCode(e.keyCode).match(/[^0-9]/) || !$return){
$("#error_msg").html("Formate type should be MM/DD/YYYY");
return false;
}
});
});
});
<script type="text/javascript" src="https://cdn.jsdelivr.net/jquery/latest/jquery.min.js"></script>
<input type="text" name="daterange" id="daterangefield" maxlength="23" value="" />
<div id="error_msg"></div>
我有 1 个输入框,我已经设置了验证,比如用户不能在输入框内输入字母和特殊字符,这对我来说工作正常。我想按照下面添加更多限制
<script type="text/javascript" src="https://cdn.jsdelivr.net/jquery/latest/jquery.min.js"></script>
<input type="text" name="daterange" id="daterangefield" maxlength="23" value="" />
<div id="error_msg"></div>
$(function() {
//Put our input DOM element into a jQuery Object
var $jqDate = jQuery('#daterangefield');
//Bind keyup/keydown to the input
$jqDate.bind('keyup','keydown', function(e){
//To accomdate for backspacing, we detect which key was pressed - if backspace, do nothing:
if(e.which !== 8) {
var numChars = $jqDate.val().length;
if(numChars === 2 || numChars === 5 || numChars === 10 || numChars === 15 || numChars === 18){
var thisVal = $jqDate.val();
if (numChars === 10) {
thisVal += ' - ';
}else{
thisVal += '/';
}
$jqDate.val(thisVal);
}
}
});
// Validate code
$(document).ready(function(){
$("#daterangefield").keypress(function (e){
var keyx = e.which;
$("#error_msg").html("");
var key = e.keyCode || e.which;
$return = (key == 8 || key == 32 || (key >= 48 && key <= 57) || (key > 64 && key < 91) || (key > 98 && key < 123) );
if(String.fromCharCode(e.keyCode).match(/[^0-9]/) || !$return){
$("#error_msg").html("Formate type should be MM/DD/YYYY");
return false;
}
});
});
});