0

I've tried multiple different ways, but I'm lost. I can't seem to remove the "Invalid Date" that gets outputted. The Invalid Date occurs because of a blank entry from the JSON. Alas, I have given a workable example without using AJAX which produces the same result.

$(document).ready(function() {

  var datePassed = "20170715";
  var inval = "";
  var newDateString = datePassed.substr(4,2)  + "-" + datePassed.substr(6,2) + "-" + datePassed.substr(0, 4);
  var finalDate = new Date(newDateString.replace(/(?:Invalid Date)/g, " "));
  var fakeDate = new Date(inval.replace(/(?:Invalid Date)/g, " "));

  console.log(finalDate);
  console.log(fakeDate);

});

Invalid Date gets appended to my HTML and it's not cool.

Edit: Some people seem to be under the impression all I want to do is validate whether or not I get an invalid date back. I expect them to come; it's simply part of how I arrange things. I want "Invalid Date" removed from my HTML as it is appended to my class like so:

this.elem.find(".deadline").append(finalDate);

Some data comes through null and some comes with an actual date. That's just how the JSON data is. I would like answers to directly address how to replace a string with regex and not use any other method.

Antonio Nogueras
  • 117
  • 1
  • 10
  • Perhaps this type of problem is not a good fit for regular expressions? – Dave Van den Eynde Jul 14 '17 at 05:27
  • Possible duplicate of [Detecting an "invalid date" Date instance in JavaScript](https://stackoverflow.com/questions/1353684/detecting-an-invalid-date-date-instance-in-javascript) – Dave Van den Eynde Jul 14 '17 at 05:32
  • @DaveVandenEynde This would suggest I only want to know if something is an invalid date. That is irrelevant to me. I simply want the result removed from the DOM as it muddies up my HTML. – Antonio Nogueras Jul 14 '17 at 05:49

2 Answers2

1

To check if Date is valid or not you can do this

var dateString = "12-12-2012";
var date = new Date(dateString);

if ( Object.prototype.toString.call(date) === "[object Date]" ) {
  if ( isNaN(date.getTime())) {/* date is not valid */}
  else {/* date is valid */}
}
umar
  • 910
  • 10
  • 24
0

Validate with simple if condition .its check empty or null

var datePassed = "20170715";
var inval = "";
var newDateString = datePassed.substr(4, 2) + "-" + datePassed.substr(6, 2) + "-" + datePassed.substr(0, 4);

console.log(valid(newDateString)); //true
console.log(valid(inval)); //false

function valid(a){
return !!a.trim()
}
prasanth
  • 22,145
  • 4
  • 29
  • 53