如何在Jquery / Javascript中限制日期和月份无效

时间:2016-07-28 06:03:02

标签: javascript jquery

这是我的代码



//Put our input DOM element into a jQuery Object
var $jqDate = jQuery('input[name="jqueryDate"]');

//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){
			var thisVal = $jqDate.val();
			thisVal += '/';
			$jqDate.val(thisVal);
		}
  }
});

<div style="font-family: Helvetica,Arial,sans-serif; font-size: 12px; line-height: 150%;">
  <strong>HTML5 "date" input type:</strong> <input type="date" name="html5date"><br>
  <strong>jQuery "date" input type mimic:</strong> <input type="text" name="jqueryDate" placeholder="dd/mm/yyyy"><br>
  Key Input: <span id="keyP">null</span>
</div>
&#13;
&#13;
&#13;

在上面的代码中我有一个文本框。在该文本框中,用户手动输入日期。它需要日期格式。但是用户输入的日期超过31和12月不接受。如何使用Jquery或Javascript来限制日期和月份。

这是Jsfiddle: - https://jsfiddle.net/ChrisCoray/hLkjhsce/

1 个答案:

答案 0 :(得分:0)

您需要添加'datePicker'作为类名

$(".datePicker").datepicker({
        dateFormat: 'd/mm/yy',
        changeMonth: true,
        changeYear: true,
        firstDay: 1,
        minDate: Date.parse("1900-01-01"),
        maxDate: Date.parse("2100-01-01"),
        yearRange: "c-90:c+150"
    });

    // validation in case user types the date out of valid range from keyboard : To fix the bug with out of range date time while saving in sql 
    $(function () {
        $.validator.addMethod(
            "date",
            function (value, element) {

                var minDate = Date.parse("1900-01-01");
                var maxDate = Date.parse("2100-01-01");
                var valueEntered = Date.parse(value);

                if (valueEntered < minDate || valueEntered > maxDate) {
                    return false;
                }
                return !/Invalid|NaN/.test(new Date(minDate));
            },
            "Please enter a valid date!"
        );
    });