Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :

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!

like image 954
Kanye West Avatar asked Oct 01 '13 07:10

Kanye West


People also ask

How do I make an empty date field in HTML?

Assuming you want to make the value shown to dd/mm/yyyy , then click on Clear button.

How do you make a date field empty?

"NULL" can be specified as a value in the Date field to get an empty/blank by using INSERT statement. Example: CREATE table test1 (col1 date); INSERT into test1 values (NULL);


2 Answers

You could check for a falsy value:

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

The falsy values in JavaScript are:

  1. undefined
  2. null
  3. false
  4. ""
  5. 0 and -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.

like image 65
Marius Schulz Avatar answered Oct 21 '22 15:10

Marius Schulz


I would try using Date.parse() if I were you.

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

if(!Date.parse(valueDate)){
  alert('date is invalid');
}

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

like image 39
Tr1stan Avatar answered Oct 21 '22 17:10

Tr1stan