简体   繁体   中英

JavaScript for Google Sheets Data Validation - custom error message

Is there any way to specify the message that goes out to the user when a cell fails the data validation? When the user inputs an invalid data, the program spits out a button saying, "There was a problem" as a title and "The data you entered in cell D2 violates the data validation rules set on this cell" as test. How can I make it say, "Improper input" as a title and then "The value must be in email format" for the body? I've tried researching this all over but can't find out how to do it.

Also - when do I have to run this? Even if the sheet is shared with other people, do I only run this function once and it will apply forever, or do I have to input it into an onOpen trigger?

Thanks! Please find my code below.

function Validate() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheets = ['Tasks', 'Sales Files Load'];

  for (var i=1; i < sheets.length; i++) { //apply the validation to specific sheets
    var sheet = ss.getSheetByName(sheets[i]); //location of User column
    var ucol = sheet.getLastColumn()-1;
    var tcol = sheet.getLastColumn(); //location of Time column
    var lastRow = sheet.getLastRow();

  // Set the data validation for column D to require text in the form of an email address.
  var cell1 = sheet.getRange(2, ucol, lastRow-1, 1);
  var rule1 = SpreadsheetApp.newDataValidation().requireTextIsEmail().setAllowInvalid(false).build();
  cell1.setDataValidation(rule1);
  }

No need for custom script if you can set the data validation from the menu directly in the spreadsheet. You just need to click the chechbox next to Show validation help text: when configuring the validation item and enter the message you wish to see.

If you wish to do this with code, add another item to your rule for the Help Text .setHelpText():

var rule1 = SpreadsheetApp.newDataValidation().requireTextIsEmail().setAllowInvalid(false)**.setHelpText('My Help Text.')**.build();

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