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

3.1k views Asked by At

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

There are 2 answers

0
Liberateur On BEST ANSWER

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

According to the relevant part of the inquirer docs, you can add a validate function:

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

}

Now you just need to write code that will return true if you get a valid email address and false otherwise. Handling all the edge cases of email addresses results in a notoriously long and complex regular expression. There are packages you can use, if you like. A quick search turned up email-validator for example. If you install it as a dependency, you can use it as your validate function.

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

...

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