I created a questionnair using Google Forms. I want to authenticate users using a simple one time password that should be entered in the first question.
The password is stored inside a spreadsheet that contains only one cell. https://prnt.sc/r8i8q1
The script below reads the content of this cell and create a custom validator against the value of the first item of the form.
function validatePassword() {
var passwordSpreadsheet = "[passwords_spreadsheet_id]";
var ss = SpreadsheetApp.openById(passwordSpreadsheet);
var passwordSheet = ss.getSheetByName("passwords");
var form = FormApp.getActiveForm();
var items = form.getItems();
var item = items[0];
if (item.getType() == 'TEXT') {
var textItem = item.asTextItem();
var namedRanges = passwordSheet.getNamedRanges();
if (namedRanges.length > 0) {
var range = namedRanges[0].getRange();
var values = range.getValues();
var currentPassword = values[0][0];
var textValidation = FormApp.createTextValidation()
.requireTextMatchesPattern(currentPassword)
.build();
textItem.setValidation(textValidation);
}
}
}
The above code is working as expected for one password, but, the problem is that I couldn't find a way to create a custom validator against range of values.
The following piece of code will make a password verification according to what you right on the Spreadsheet as a password. It has comments to explain what line of code does:
function validatePassword() {
// Create new custom form
var form = FormApp.create('New Form');
var ss = SpreadsheetApp.openById('SHEETID');
var password = ss.getSheetByName('SHEETNAME').getRange('A1').getValue();
// Create first question to check the password, it must be required so that the user does not have access to the rest
// of the form if failed to log in
var item = form.addTextItem().setRequired(true);
item.setTitle('TEST TITLE');
// Create validation for this question matching the password that we got from the sheet
var textValidation = FormApp.createTextValidation()
.setHelpText('You must enter the right password')
.requireTextMatchesPattern(password)
.build();
item.setValidation(textValidation);
}
The esieast way to validate forms with password is to use the custom functionalities of Google forms. In your case you should follow these steps:
In the first section of your form only place a required short text answer.
Go to the three dots in the lower right part of the question and select Response Validation
Regular expression
, Matches
and introduce your desired regular expression (it could just be a String) and the right error message. Here is an example of this in action:
I hope this has helped you. Let me know if you specifically need to get the passwords from the Spreadsheet. Let me know if you need anything else or if you did not understood something. :)