Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
313 views
in Technique[技术] by (71.8m points)

node.js - How to prevent float and negative input using Javascript?

I'm using readlineSync.questionInt and I need to prompt a message if the user types float or negative number. I used a limit, but it isn't enough.

var readlineSync = require('readline-sync');
var number_of_people = readlineSync.questionInt('How many people are you going with?', { limit: 0 - 9 });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I would use just question and move your custom login into limit callback. For instance, one idea could be checking if the input is an integer and it is in the range between 0-9:

var readlineSync = require('readline-sync');
var number_of_people = readlineSync.question('How many people are you going with?', {
  limit: function(i) {
    const input = Number(i);
    return  Number.isInteger(input) && input > 0 && input < 10;
}});

You could also make use of regexp; just have your callback return true when the input is valid based on your logic


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...