[英]how to check if the input data in google spreadsheet is a valid Date type by GAS
I am working on Google Apps Script.我正在研究 Google Apps 脚本。
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.
用户输入或编辑应以有效日期格式输入的数据(例如 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());
}
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.
当输入“2020/5/5”时,会弹出警报。 And,
Logger.log(str);//output: 43956
.而且,
Logger.log(str);//output: 43956
。
Try doing your onEdit() like this:尝试像这样进行 onEdit() :
Use e.range.getValue() instead of e.value.使用 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]');
}
I've noticed a difference between e.value and e.range.getValue() sometimes.我有时注意到 e.value 和 e.range.getValue() 之间的区别。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.