0

我正在使用 nodeJS 和查询器来生成一个包含用户输入的详细信息的 html。这只是代码片段,但我可以添加一些内容以确保在电子邮件问题中他们实际上以电子邮件格式给出答案?

inquirer.prompt([
                {
            type: 'list',
            messaage: 'What is your role?',
            name: 'role',
            choices: ['Manager', 'Engineer', 'Intern']
        },{
            type: 'input',
            message: 'What is your name?',
            name: 'name'
        },{
            type: 'input',
            message: 'What is your ID number?',
            name: 'id'
        },{
            type: 'input',
            message: 'What is your email address?',
            name: 'email'
//What would go here to validate that an email address was entered?
    },
])
4

2 回答 2

1

有一个“验证”方法可以使用函数验证字段。只需添加一个正则表达式邮件测试,试试这个:

inquirer.prompt(
[
    {
        type: 'list',
        messaage: 'What is your role?',
        name: 'role',
        choices: ['Manager', 'Engineer', 'Intern']
    },
    {
        type: 'input',
        message: 'What is your name?',
        name: 'name'
    },
    {
        type: 'input',
        message: 'What is your ID number?',
        name: 'id'
    },
    {
        type: 'input',
        message: 'What is your email address?',
        name: 'email',
        validate: function(email)
        {
            // Regex mail check (return true if valid mail)
            return /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()\.,;\s@\"]+\.{0,1})+([^<>()\.,;:\s@\"]{2,}|[\d\.]+))$/.test(email);
        }
    }
]);
于 2020-12-07T23:05:18.443 回答
0

根据文档的相关部分inquirer,您可以添加一个validate功能:

{
        type: 'input',
        message: 'What is your email address?',
        name: 'email',
        validate: function (input) { // Validate here }

}

现在您只需要编写代码,true如果您获得有效的电子邮件地址或false其他情况,该代码将返回。处理电子邮件地址的所有边缘情况会导致众所周知的长而复杂的正则表达式。如果您愿意,可以使用一些软件包。例如,出现了快速搜索email-validator。如果将其安装为依赖项,则可以将其用作验证功能。

const emailValidator = require('email-validator');

...

  {
        type: 'input',
        message: 'What is your email address?',
        name: 'email',
        validate: emailValidator
  }
于 2020-12-07T23:04:44.900 回答