Arun Elangovan
Arun Elangovan

Reputation: 237

How to validate an numeric input in Node js?

I'm trying a build a simple calculator in node.js which also should validate the inputs. Below is the following code

process.stdout.write('A simple calculator created using node.js \n');

var inputs = ['Please enter your first number','Please enter the second number','Please enter the operator'];
var output1 = [];

function ask(i) {
	process.stdout.write(`${inputs[i]}`);
	process.stdout.write(" : ");
}
ask(0);
process.stdin.on('data',(data)=> {
	if(typeof data != "number"){
		console.log(ask(0));
	} else {
	output1.push(data); 
	console.log('The given input is ' + output1);
}
}
);

I would want the console to loop back to the function ask() if my input is not a number. Below should be the ideal output

Output : Please enter your first number : p Please enter your first number : 1 The given input is 1

I know there are some flaws in my code, but not sure how to correct it. Pls help.

Upvotes: 0

Views: 7339

Answers (1)

Anand Undavia
Anand Undavia

Reputation: 3543

The callback to process.stdin.on will receive the Buffer object as the argument.

process.stdin.on('data', data => {
    /** data will be buffer. */
});

You will need to convert the Buffer to String using toString() method. Once you have the String, you can try to parse the string to a number (Int or Float) using methods of Number class ( Number.parseInt or Number.parseFloat ). You can then check if the number you parsed was a valid number or not using Number.isNaN method.

Here is how the code would look like:

process.stdin.on('data', data => {
    var string = data.toString();
    var number = Number.parseFloat(string);
    if (Number.isNaN(number)) {
        ask(0);
    } else {
        output1.push(number);
        console.log('The given input is ' + output1);
    }
});

To give you a hint on how to finish the whole calculator, I would create a indexOfInput and maintain it on the inputs:

var indexOfInput = 0;
ask(indexOfInput);
process.stdin.on('data', data => {
    var string = data.toString();
    var number = Number.parseFloat(string);
    if (Number.isNaN(number)) {
        ask(indexOfInput);
    } else {
        output1.push(number);
        console.log('The given input is ' + output1);
        // Current input taken successfully. Let's take the next input
        indexOfInput++;
        ask(indexOfInput);
    }
});

You will need to further add make tweaks to make it work completely. You will need something like this somewhere in your code.

if (indexOfInput <= 1) {
    /** expecting number */
} else if (indexOfInput === 2) {
    /** expecting an operator */
} else {
    /** all the inputs taken. process the inputs array */
}

Hope this helps! :)

Upvotes: 2

Related Questions