javascript 验证日期输入 - 最小值和最大值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19773931/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Validation date input - min and max value
提问by witek1902
I have one little problem with HTML5.
我对 HTML5 有一个小问题。
<input type="date" id="birthday" />
I want check this field in JavaScript.
我想在 JavaScript 中检查这个字段。
Min. value - 01-01-1990.
最小 值 - 01-01-1990。
I have no idea how to parse the date object and check that is correct.
我不知道如何解析日期对象并检查它是否正确。
Attribute min and max in HTML5 is not working. I must write validation in JavaScript.
HTML5 中的属性 min 和 max 不起作用。我必须用 JavaScript 编写验证。
回答by Jan
You can use a JavaScript validation library, which uses the HTML5 input attributes like min and max: for example jQuery Validation:
您可以使用 JavaScript 验证库,它使用 HTML5 输入属性,如 min 和 max:例如jQuery Validation:
<input id="mydate" name="mydate" type="date" min="2000-01-01" max="2010-31-12" required />
<script>
$("#mydate").validate();
</script>
Have a look as this fiddle for a working example: http://jsfiddle.net/a5Mvt/1/
看看这个小提琴的工作示例:http: //jsfiddle.net/a5Mvt/1/
In addition you might want to use a library like Modernizrto check for browser support of input[type="date"]
and use a datepicker control from jQuery UIor something similar, if it is not supported.
此外,如果不支持,您可能希望使用像Modernizr这样的库来检查浏览器是否支持input[type="date"]
并使用来自jQuery UI或类似控件的日期选择器控件。
Update:Here's a version, that doesn't use jQuery or any other additional library:
更新:这是一个不使用 jQuery 或任何其他附加库的版本:
<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>
Updated fiddle: http://jsfiddle.net/a5Mvt/2/
更新小提琴:http: //jsfiddle.net/a5Mvt/2/