我正在尝试在日期验证时抛出错误,
如果日期为空,则日期不能早于当前日期。

我已经尝试过:

var olddate = new Date("Fri Sep 22 2016");


var currentdate = new Date();

if(olddate > currentdate)
{
document.write("date is older than curent date");
//how to throw error here
}

else if( olddate ==null || olddate =="")
{
document.write("date is null or empty");
//how to throw error here
}

else
{


document.write(currentdate);
}

最佳答案

您可以使用构造函数new Error("Date is null or empty.")创建Error,您可以在其中将错误消息作为参数传递。然后,您可以将其作为throw err抛出。



var olddate = new Date("Fri Sep 29 2018");
var currentdate = new Date();

if (olddate > currentdate) {
  document.write("date is older than curent date");

  var err = new Error("Date is older than curent date.");
  throw err;
} else if (olddate == null || olddate == "") {
  document.write("date is null or empty");

  var err = new Error("Date is null or empty.");
  throw err;
} else {
  document.write(currentdate);
}

关于javascript - 在JavaScript中错误抛出日期,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46398405/

10-08 20:32