验证日期输入 - 最小值和最大值 [英] Validation date input - min and max value
问题描述
我有一个HTML5的问题。
I have one little problem with HTML5.
<input type="date" id="birthday" />
我想在JavaScript中检查此字段。
I want check this field in JavaScript.
最小值 - 01-01-1990。
Min. value - 01-01-1990.
我不知道如何解析日期对象并检查是否正确。
I have no idea how to parse the date object and check that is correct.
HTML5中的属性最小值和最大值不起作用。我必须在JavaScript中编写验证。
Attribute min and max in HTML5 is not working. I must write validation in JavaScript.
推荐答案
您可以使用JavaScript验证库,它使用HTML5输入属性,如min和max :例如 jQuery验证:
You can use a JavaScript validation library, which uses the HTML5 input attributes like min and max: for example jQuery Validation:
<input id="mydate" name="mydate" type="date" min="2000-01-01" max="2010-31-12" required />
<script>
$("#mydate").validate();
</script>
看看这个小提琴为一个工作示例: http://jsfiddle.net/a5Mvt/1/
Have a look as this fiddle for a working example: http://jsfiddle.net/a5Mvt/1/
另外你可能会想使用像 Modernizr 这样的图书馆检查浏览器支持 input [type =date]
,并使用 jQuery UI 中的datepicker控件或类似的东西(如果不支持) 。
In addition you might want to use a library like Modernizr to check for browser support of input[type="date"]
and use a datepicker control from jQuery UI or something similar, if it is not supported.
更新:这是一个版本,不使用jQuery或任何其他附加图书馆:
Update: Here's a version, that doesn't use jQuery or any other additional library:
<input id="mydate" name="mydate" type="date" min="2000-01-01" max="2010-31-12" required />
<span id="mydate_error" style="display:none;"></span>
<script>
var mydate = document.getElementById('mydate'),
mydateError = document.getElementById('mydate_error');
mydate.addEventListener('input', function() {
if (!mydate.value.match(/\d{4}-\d{1,2}-\d{1,2}/)) {
mydateError.innerHTML = 'Please specify a valid date in the form 1990-02-22';
mydateError.style.display = 'inherit';
} else {
var value = new Date(mydate.value),
min = new Date(mydate.min),
max = new Date(mydate.max);
if (value < min || value > max) {
mydateError.innerHTML = 'Date has to be between ' + min.toDateString() + ' and ' + max.toDateString();
mydateError.style.display = 'inherit';
} else {
mydateError.style.display = 'none';
}
}
});
</script>
更新小提琴: http://jsfiddle.net/a5Mvt/2/
这篇关于验证日期输入 - 最小值和最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!