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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 14:23:16  来源:igfitidea点击:

How to check the (empty) value of a input type="date" in Chrome

javascriptinput

提问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 的六个假值是

  1. undefined,
  2. null,
  3. false,
  4. the empty string,
  5. 0(of type number), and
  6. NaN.
  1. undefined,
  2. null,
  3. false,
  4. 空字符串,
  5. 0(类型number),和
  6. NaN.

Since document.getElementById('Date').valueis always of type string if a value is set, you don't get false positives like 0being 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');
}

http://www.w3schools.com/jsref/jsref_parse.asp

http://www.w3schools.com/jsref/jsref_parse.asp