Date Validation in google forms with App Script

If you're using a Google Form where respondents must select a date, you cannot restrict them to choose only within a specific date range. While you can add instructions to your form, respondents who prefer not to read may overlook them. This script allows you to populate a multiple-choice question with dates, enabling you to define a start and end date to guide your respondents.

One might wonder, 'Why not just type out the dates?' The advantage of using a script is that once implemented, it can be used indefinitely. This is particularly useful if you frequently organize events. With the script already set up, you save time and effort compared to manually entering dates each time.

Watch the accompanying video tutorial and follow the provided .gs and .html code examples to implement this script in your Google Form.

    
      // Code.gs

function openSidebar() {
var html = HtmlService.createHtmlOutputFromFile('sidebar')
  .setTitle('Date Input Sidebar')
  .setWidth(300);
FormApp.getUi().showSidebar(html);
}

function populateDateOptions(startDate, endDate) {
var form = FormApp.getActiveForm();
var item = form.getItems(FormApp.ItemType.MULTIPLE_CHOICE)[0].asMultipleChoiceItem();

var dateOptions = generateDateOptions(startDate, endDate);
item.setChoiceValues(dateOptions);
}

function generateDateOptions(startDate, endDate) {
var dateOptions = [];
var currentDate = new Date(startDate);
var endDateObj = new Date(endDate);

while (currentDate <= endDateObj) {
  var formattedDate = Utilities.formatDate(currentDate, Session.getScriptTimeZone(), 'dd-MM-yyyy');
  dateOptions.push(formattedDate);
  currentDate.setDate(currentDate.getDate() + 1); // Increment date by 1 day
}

return dateOptions;
}
    
    Copy Code
  
    
      
      <!DOCTYPE html>
      <html>
      <head>
        <base target="_top">
      </head>
      <body>
        <label for="startDate">Start Date:</label>
        <input type="date" id="startDate" name="startDate"><br><br>
        <label for="endDate">End Date:</label>
        <input type="date" id="endDate" name="endDate"><br><br>
        <button onclick="populateDates()">Populate Dates</button>

        <script>
          function populateDates() {
            var startDate = document.getElementById('startDate').value;
            var endDate = document.getElementById('endDate').value;

            google.script.run.withSuccessHandler(function() {
              alert('Dates populated successfully!');
            }).populateDateOptions(startDate, endDate);
          }
        </script>
      </body>
      </html>
    
    Copy Code
  
Boton Flotante - WhatsApp