The simplest answer is to use Data Validation, not a script, to control what people can enter in the date column.
- Select the column.
- Select Format > Number > More Formats > More Date and Time Formats.
- Select the format that you want for your column.
- Click Apply.
- Shift-click on the header to remove it from the selected area.
- Select Data > Data Validation.
- Select Criteria: Date is valid date.
- Select Reject input.
- Click the Appearance checkbox.
- Enter help text, for example, "Enter a valid date in the format YYYY-mm-dd."
- Click Save.
If you're concerned about people removing the data validation intentionally or by pasting a value into the cell, you may use the following script for a value captured from onEdit to check if the value is a date.
const cols = {
"date": 2 // column number that contains date
}
function onEdit(e) {
let range = e.range;
let col = range.getColumn();
if (col == cols.date) {
let value = range.getValue();
let newDate = new Date(value);
let timeCheck = newDate.getTime();
let isTime = (timeCheck === timeCheck);
if (!isTime) {
let message = "'" + value + "' is not a date. Please enter a valid date.";
let ui = SpreadsheetApp.getUi();
ui.alert(message);
range.setValue(""); // or however you want to handle a date error
}
}
}
If the value is not a valid date, the time returned from it is NaN, and NaN never equals itself. e will have the old and new values of the cell, so you can correct it and reapply validation if needed.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…