简体   繁体   中英

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

I am working on Google Apps Script.

I want to check the cell value if the value is valid date. User inputs or edits data that should be input in valid date format(eg. 2020/05/25), and then an installable trigger that is triggered when onEdit is executed to check the cell value.

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());
}

but, it doesn't work as expected. What is wrong with it?

According to the answer, I tried this.

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]');
}

but it doesn't work. When input "2020/5/5", alert pops up. And, Logger.log(str);//output: 43956 .

Try doing your onEdit() like this:

Use e.range.getValue() instead of 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]');
}

I've noticed a difference between e.value and e.range.getValue() sometimes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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