繁体   English   中英

如何检查谷歌电子表格中的输入数据是否是 GAS 的有效日期类型

[英]how to check if the input data in google spreadsheet is a valid Date type by GAS

我正在研究 Google Apps 脚本。

如果值是有效日期,我想检查单元格值。 用户输入或编辑应以有效日期格式输入的数据(例如 2020/05/25),然后在执行 onEdit 时触发可安装触发器以检查单元格值。

function checkData_colA(e){
  //there are some other codes.
  ...

  var str = e.value;
  var range = e.range;

  //ignore check when str is empty.
  if(str !== "" && !isValidDate(date)){
    //pop up alert      
  }
}

// From http://stackoverflow.com/questions/1353684
// Returns 'true' if variable d is a date object.
function isValidDate(d) {
  if ( Object.prototype.toString.call(d) !== "[object Date]" )
    return false;
  return !isNaN(d.getTime());
}

但是,它没有按预期工作。 它有什么问题?

根据答案,我尝试了这个。

function checkData_colA(e){
  //there are some other codes.
  ...

  var str = e.value;
  var range = e.range;

  Logger.log(str);//output: 43956

  //ignore check when str is empty.
    if(str !== "" && !isDate(date)){
      //pop up alert      
    }
  }

function isDate(date){
  return(Object.prototype.toString.call(date) === '[object Date]');
}

但它不起作用。 当输入“2020/5/5”时,会弹出警报。 而且, Logger.log(str);//output: 43956

尝试像这样进行 onEdit() :

使用 e.range.getValue() 代替 e.value。

function onEdit(e){
  const sh=e.range.getSheet();
  if(sh.getName()=='Sheet1'&& e.range.columnStart==1 && e.value) {
    if(isDate(e.range.getValue())) {
      e.source.toast('Yip');
    }else{
      e.source.toast('Nope');
    }
  }
}

function isDate(date){
  return(Object.prototype.toString.call(date) === '[object Date]');
}

我有时注意到 e.value 和 e.range.getValue() 之间的区别。

暂无
暂无

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

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