node.jsnpminquirer

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


I'm using nodeJS and inquirer to generate an html that contains the details the user enters. This is just a snippet of the code but is there something I could add to make sure that in the email question they actually give an answer in email format?

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?
    },
])

Solution

  • There is a "validate" method which validates the field with a function. Just add a Regex mail test, try this :

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