Функция генерации пароля, содержащая не менее 1 цифры, 1 заглавной буквы и 1 строчной буквы

#javascript #google-apps-script #google-sheets

#javascript #google-apps-script #google-таблицы

Вопрос:

У меня есть функция, генерирующая случайный пароль, состоящий из букв и цифр.

Я хотел бы иметь не менее 1 цифры, 1 заглавной буквы и 1 строчной буквы. У вас есть какие-либо идеи?

Вот мой код :

 // Range of letters and numbers to include in the password
// Modify if needed to add or remove characters
var PASSWORD_CHARS_RANGE = "abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ123456789";

/**
* Return a randomly generated password of the given length. If no length is provided, defaults to 8.
*
* @param {number} length (Optional) The length of the password - Default is 8 characters
* @return A password
* @customfunction
*/

function PASSWORD(length){
  
  var passwordLength = 8;
  var password = "";
  
  // Do some checks on the params
  if ((typeof length !== "undefined") amp;amp; ((length >= 1) amp;amp; (typeof length === "number") amp;amp; Math.floor(length) === length)){
    passwordLength = length;
  }
  
  // Add random characters to the password string
  for (var i = 0; i < passwordLength; i   ){
   password  = PASSWORD_CHARS_RANGE.charAt(Math.random() * PASSWORD_CHARS_RANGE.length);
  }
  
  return password;
} 

Спасибо!

Комментарии:

1. Какие шаги вы предприняли, чтобы попытаться что-то реализовать?

2. Сохраняйте только строчные буквы и цифры в строке PASSWORD_CHARS_RANGE. Используйте массив и вставляйте случайные символы в массив для определения длины или преобразуйте сгенерированную строку в массив символов. Проверьте наличие 1 числа в массиве, чтобы удовлетворить вашему условию. Обновите случайные символы до верхней строки.

Ответ №1:

Вы можете удалить заглавные символы и цифры PASSWORD_CHARS_RANGE , а затем добавить этот сегмент кода для преобразования строчных символов в прописные и цифры:

   // change random number of characters (1 to length-2) to uppercase
    var uc = Math.ceil(Math.random()*(passwordLength-2));
    for (var j = 0; j < uc; j  ) {
      var idx1 = Math.floor(Math.random()*(passwordLength-1));
      password = password.substr(0,idx1) password.charAt(idx1).toUpperCase() password.substr(idx1 1); 
    }
    
  // change random number of characters (1 to length-uc-1) to numbers
    var un = Math.ceil(Math.random()*(passwordLength-uc-1));
    for (var k = 0; k < un; k  ) {
      var idx2 = Math.floor(Math.random()*(passwordLength-1));
      if (password.charAt(idx2) === password.charAt(idx2).toLowerCase()) {
         password = password.substr(0,idx2) String(Math.floor(Math.random()*10)) password.substr(idx2 1);
      }
      else --k;
    }
 

Запуск функции на листе с образцом дает:

введите описание изображения здесь

Ответ №2:

Manohar407278512

 // Range of letters and numbers to include in the password
// Modify if needed to add or remove characters
var PASSWORD_CHARS_RANGE = "abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ123456789";

/**
* Return a randomly generated password of the given length. If no length is provided, defaults to 8.
*
* @param {number} length (Optional) The length of the password - Default is 8 characters
* @return A password
* @customfunction
*/

function PASSWORD(length){
  
  var passwordLength = 8;
  var password = "";
  
  // Do some checks on the params
  if ((typeof length !== "undefined") amp;amp; ((length >= 1) amp;amp; (typeof length === "number") amp;amp; Math.floor(length) === length)){
    passwordLength = length;
  }
  
  // Add random characters to the password string
  for (var i = 0; i < passwordLength; i   ){
   password  = PASSWORD_CHARS_RANGE.charAt(Math.random() * PASSWORD_CHARS_RANGE.length);
  }
  
  return password;
} 
 // Range of letters and numbers to include in the password
// Modify if needed to add or remove characters
var PASSWORD_CHARS_RANGE = "abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ123456789";

/**
* Return a randomly generated password of the given length. If no length is provided, defaults to 8.
*
* @param {number} length (Optional) The length of the password - Default is 8 characters
* @return A password
* @customfunction
*/

function PASSWORD(length){
  
  var passwordLength = 8;
  var password = "";
  
  // Do some checks on the params
  if ((typeof length !== "undefined") amp;amp; ((length >= 1) amp;amp; (typeof length === "number") amp;amp; Math.floor(length) === length)){
    passwordLength = length;
  }
  
  // Add random characters to the password string
  for (var i = 0; i < passwordLength; i   ){
   password  = PASSWORD_CHARS_RANGE.charAt(Math.random() * PASSWORD_CHARS_RANGE.length);
  }
  
  return password;
}