javascript 如何在 Chrome 中检查 input type="date" 的(空)值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19110663/
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
How to check the (empty) value of a input type="date" in Chrome
提问by Kanye West
I want to check if the user entered a date. But I can't figure it out how to do it.
我想检查用户是否输入了日期。但我不知道该怎么做。
Here's some javascript code what i already got but doesn't work :
这是我已经得到但不起作用的一些 javascript 代码:
var valueDate = document.getElementById('Date').value;
if ( valueDate== null || valueDate== '')
{
alert('Date is empty');
return false;
}
And the HTML <input type="date" name="Date" id="Date"/>
Thanks in advance!
和 HTML<input type="date" name="Date" id="Date"/>
提前致谢!
回答by Marius Schulz
You could check for a falsy value:
你可以检查一个假值:
if (!valueDate) {
// ...
}
The six falsy values of JavaScript are
JavaScript 的六个假值是
undefined
,null
,false
,- the empty string,
0
(of typenumber
), andNaN
.
undefined
,null
,false
,- 空字符串,
0
(类型number
),和NaN
.
Since document.getElementById('Date').value
is always of type string if a value is set, you don't get false positives like 0
being treated like no input, which would be the case if the type was number
.
由于document.getElementById('Date').value
如果设置了值,则始终为字符串类型,因此您不会得到误报,例如0
被视为没有输入,如果类型为number
.
回答by Tr1stan
I would try using Date.parse() if I were you.
如果我是你,我会尝试使用 Date.parse()。
var valueDate = document.getElementById('Date').value;
if(!Date.parse(valueDate)){
alert('date is invalid');
}