Search code examples
javascriptformsvalidationgoogle-apps-script

Google Scripts Forms - Update input validation


I have a Google Form and an associated script (already connected via Deploy etc). The form serves as a sort of exam that is protected by a Password. The idea is to regenerate this Password with a code after each Submit and to replace the old Password with newPassword. However, I get this code here and ask for help.

enter image description here

function onFormSubmit(e) {
  console.log('Form submission received.');

  var form = FormApp.getActiveForm();
  var response = e.response;
  var items = form.getItems();

  // Find the password input field by its title
  var passwordFieldTitle = 'Password';
  var passwordField = null;

  for (var i = 0; i < items.length; i++) {
    if (items[i].getTitle() === passwordFieldTitle) {
      passwordField = items[i];
      break;
    }
  }

  if (passwordField === null) {
    console.log('Password field not found.');
    return;
  }

  // Get the password input value
  var itemResponses = response.getItemResponses();
  var passwordInputValue = null;

  for (var j = 0; j < itemResponses.length; j++) {
    if (itemResponses[j].getItem().getTitle() === passwordFieldTitle) {
      passwordInputValue = itemResponses[j].getResponse();
      break;
    }
  }

  if (!passwordInputValue) {
    console.log('Password field value is missing.');
    return;
  }

  // Generate a new password
  var newPassword = generatePassword();

  // Update the input validation for the password field
  var validation = FormApp.createTextValidation()
    .setHelpText('Please enter the new password as displayed in the form help text.')
    .requireTextContains('New Password: ' + newPassword)
    .build();

  passwordField.asTextItem().setValidation(validation);

  // Check if the password matches the stored password
  var isValidPassword = passwordInputValue.includes('New Password: ' + newPassword);

  if (!isValidPassword) {
    console.log('Invalid password. Please try again.');
    form.setCustomClosedFormMessage('Invalid password. Please try again.');
    return;
  }

  // Send a Discord webhook with the new password
  sendDiscordWebhook(newPassword);
}

function generatePassword() {
  var length = 12; // Length of the password
  var characters =
    'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789&@/-?'; // Allowed characters for the password
  var password = '';

  for (var i = 0; i < length; i++) {
    var randomIndex = Math.floor(Math.random() * characters.length);
    password += characters.charAt(randomIndex);
  }

  return password;
}

function sendDiscordWebhook(password) {
  console.log('Sending Discord webhook with the new password.');

  var payload = {
    embeds: [
      {
        title: 'New Password',
        description: 'The password has been changed.',
        fields: [
          {
            name: 'Password',
            value: password,
          },
        ],
      },
    ],
  };

  var options = {
    method: 'post',
    contentType: 'application/json',
    payload: JSON.stringify(payload),
  };

  UrlFetchApp.fetch(discordWebhookUrl, options);

  console.log('Discord webhook sent successfully.');
}

[1] This is the Password which is to be replaced with newPassword after submit

enter image description here

How can I solve this? I've already tried other things like RegEx, but I'd better stay away from RegEx ;)


Solution

  • requireTextContains is not a valid method for "Forms".

    Use instead:

    • requireTextContainsPattern() doc ref, or
    • requireTextMatchesPattern doc ref

    Since this is a password, I'd put my money on requireTextMatchesPattern