将用户输入与REGEX匹配

时间:2018-02-18 18:10:14

标签: javascript google-apps-script

也许主题行不正确,但这是我的问题:

我正在尝试查看用户输入是否是有效的电子邮件地址,或者首先是否有输入。如果以上都不是,那么我想循环再次请求答案的问题,直到我得到一个有效的答案(在这种情况下,电子邮件地址)。下面是我编写的代码,直到我添加了REGEX测试。

    function emailPrompt() {

   var ui = SpreadsheetApp.getUi();
  var entry = ui.prompt("REQUIRED: Email Address", "Please type the email address you want the exported excel spreadsheet to be emailed to:"+"\n\n", ui.ButtonSet.OK);
  var button = entry.getSelectedButton();
  var response = entry.getResponseText();

  var sum = 1;
  for(var i=0;i<sum;i++){

  var regex = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
  var matchRegex = regex.test(response);
      if(response == ""||response == " "|| response != matchRegex) {
        if(!matchRegex) { ui.alert("Invalid Email Address")}
       ui.prompt("REQUIRED: Email Address", "Please type the email address you want the exported excel spreadsheet to be emailed to:"+"\n\n", ui.ButtonSet.OK);

      sum++;
    } else {

    sum--;

    }
  }
  return response;
  Logger.log(response);
}

具体来说,如果输入不正确/无效的电子邮件地址,我插入另一个if语句来提醒用户。我很肯定我在REGEX匹配/测试中的某处乱码了。任何帮助将非常感激。 TIA

1 个答案:

答案 0 :(得分:1)

您的正则表达式声明没问题。它测试并返回一个布尔值。你的第一个if语句有点多余。 response == ""||response == " "|| response != matchRegex其中大部分已经通过正则表达式语句进行了测试,并且最后一个应该永远不会为假,因为您要将字符串与布尔值进行比较。

编辑:此外,响应变量永远不会使用新的提示数据更新(代码已更新)。

function emailPrompt() {

  var ui = SpreadsheetApp.getUi();
  var entry = ui.prompt("REQUIRED: Email Address", "Please type the email address you want the exported excel spreadsheet to be emailed to:"+"\n\n", ui.ButtonSet.OK);
  var button = entry.getSelectedButton();
  var response = entry.getResponseText();

  var sum = 1;
  for(var i=0;i<sum;i++){

    var regex = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
    var matchRegex = regex.test(response);

    if(!matchRegex) { 
      ui.alert("Invalid Email Address");

      //Ask for email again and set new response.
      var responseItem = ui.prompt("REQUIRED: Email Address", "Please type the email address you want the exported excel spreadsheet to be emailed to:"+"\n\n", ui.ButtonSet.OK);
      response = responseItem.getResponseText();

      sum++;
    } 

    //sum--; this isn't needed to stop the loop.

    if(sum > 3) //You shouldn't go on forever... Stop after a few tries?
      break;
  }
  Logger.log(response); //Moved above return so this code runs.
  return response;
}