我有这个datepicker
,它被定义为date-picker
类。
我想检查日期是否有效,我的意思是当用户通过键盘修改日期时,例如,如果输入的日期超过 31 或月份超过 12,则应该给出错误。
我已经编写了这个 isValidDate 函数,但它不能正常工作。我在某处读到,日期选择器有一个 valid()
函数。
$(function() {
$(".date-picker").datepicker({
dateFormat: 'dd/mm/yy'
});
$(".date-picker").each(function() {
$(this).add($(this).next()).wrapAll('<div class="imageInputWrapper"></div>');
});
$('input:button').click(function(e) {
$("#fDate").removeClass("red");
var fromDate = $("#fDate").val();
if (!isValidDate(fromDate)) {
$("#fDate").addClass("red");
}
if (errors) e.preventDefault();
});
function isValidDate(date) {
var matches = /^(\d{2})[-\/](\d{2})[-\/](\d{4})$/.exec(date);
if (matches == null) return false;
var d = matches[2];
var m = matches[2];
var y = matches[3];
if (y > 2100 || y < 1900) return false; // accept only recent & not too far years
var composedDate = new Date(y, m, d);
return composedDate.getDate() == d && composedDate.getMonth() == m && composedDate.getFullYear() == y;
}
});
.imageInputWrapper {
width: 172px;
border: solid 1px white;
background-color: white;
display: flex;
align-items: center;
box-shadow: 0 2px 2px 0 #C2C2C2;
}
.red {
box-shadow: 0px 0px 2px 2px red;
}
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<script src="https://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<form>
<input id="fDate" class="date-picker" type="text" name="fromDate" style="width: 130px; height: 41px; background-color: white; border: none; outline: none; margin-left:5px" />
<img src="http://s9.postimg.org/nl2mcq2rv/calendar.png" id="fromDateImgId">
<br/>
<input type="button" value="submit">
</table>
</form>
如果您在日期部分插入 44,它不会在我的代码中给出任何错误。
最佳答案
您可以使用 Date.parse()
作为验证函数。
示例
function isValidDate(str) {
return !isNaN(Date.parse(str));
}
关于javascript - datepicker valid() 函数检查日期是否有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36352729/