5
const inquirer = require("inquirer")

var questions = [
  {
    type: "number",
    name: "name",
    message: "Please the number of players",
    validate: function (name) {
      var valid = Number.isInteger(name)
      return valid || `Please enter a valid whole number`
    },
  },
]

function promptUser() {
  inquirer
    .prompt(questions)
    .then((answers) => {
      console.log(`You entered ${answers["name"]}!`)
    })
    .catch((error) => console.log(`Please enter a number`))
}

promptUser()

Considering the code above, I've noticed in older videos like this that if you include validate and it fails, the input will be cleared. In my case however, I am getting an NaN that's not automatically cleared. Let's say I start the app and input 'abcdefg':

? Please the number of players NaN
>> Please enter a valid whole number

If i type anything, it will just be added onto the end of NaN. Backspace and delete wont remove the NaN, however it will be removed if i press the up arrow button several times until no more previous inputs show up. Am i doing something wrong?

hgb123
  • 13,869
  • 3
  • 20
  • 38
Shah
  • 75
  • 1
  • 5

2 Answers2

3

I found changing the type from number to input do the trick. Here's an example of a prompt i used.

{
    type: "input",
    message: "Please enter id:",
    name: "id",
    validate: (answer) => {
      if (isNaN(answer)) {
        return "please enter a number";
      }
      return true;
    },
  },
sandy ruby
  • 31
  • 2
1

It is really annoying that it won't clear the input and also the input is blocked somehow. The way that I resolved this is wit a validation function that implements the filter function as well:

const validateNumbers = moreValidationChecks => ({
    validate: input => {
        if (input === '') {
            return 'Please provide a valid number greater then 0'
        }
        return moreValidationChecks ? moreValidationChecks(input) : true
    },
    filter: input => {
        // clear the invalid input
        return Number.isNaN(input) || Number(input) <= 0 ? '' : Number(input)
    },
})

after that just add this to the inquiry you want:

return inquirer.prompt([
    {
        name: 'amount',
        message: 'Type a number please',
        type: 'number',
        ...validateNumbers(),
    },
])

you can also pass additional validation to this:

   return inquirer.prompt([
        {
            name: 'amount',
            message: 'Type a number please',
            type: 'number',
            ...validateNumbers(input => {
                if (Number(input) < 10)) {
                    return "This must be less then 10"
                }
                return true
            }),
        },
    ])

However I am also stuck whenever you pass a valid number that throws a validation error it still can't be deleted. You need to type some text and then it will be deleted as this will make it NaN

Rangel Stoilov
  • 106
  • 1
  • 10