使用 Inquirer npm 时如何验证用户是否输入了他们的电子邮件?

How can I validate that a user input their email when using Inquirer npm?

我正在使用 nodeJS 和 inquirer 生成一个 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?
    },
])

根据the relevant part of the inquirer docs,可以添加一个validate函数:

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

}

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

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

...

  {
        type: 'input',
        message: 'What is your email address?',
        name: 'email',
        validate: emailValidator
  }

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

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);
        }
    }
]);