简体   繁体   English

如何在 Chrome 中检查 input type="date" 的(空)值

[英]How to check the (empty) value of a input type=“date” in Chrome

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"/>提前致谢!

You could check for a falsy value:你可以检查一个假值:

if (!valueDate) {
    // ...
}

The falsy values in JavaScript are: JavaScript 中的假值是:

  1. undefined
  2. null
  3. false
  4. ""
  5. 0 and -0 0-0
  6. 0n
  7. 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始终是 string 类型,如果设置了值,您不会得到像0被视为没有输入的误报,如果类型是number就会出现这种情况。

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

I would do this我会这样做

var valueDate = document.getElementById('Date').value;

if (!valueDate) {
  alert('date is invalid');
}else{alert('date is valid')}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM