Reputation: 305
I'm making a simple quadratic equation app, the user should enter a three number first: a, b and c.
The first step is checking if all input values are numbers, unfortunately, the function I wrote isn't working. How can I rewrite my function so it console.log 'Input valid data' if the input value is not a number.
Here is my code:
const a_number = parseFloat(prompt("Please, enter a-number", '0'));
const b_number = parseFloat(prompt("Please, enter b-number", '0'));
const c_number = parseFloat(prompt("Please, enter c-number", '0'));
console.log(a_number, b_number, c_number);
ValidInput(a_number, b_number, c_number);
function ValidInput (a, b, c) {
if (a || b || c) {
return
} else {
console.log('Invalid input data');
}
}
Upvotes: 1
Views: 78
Reputation: 163207
You might also add the parameters your want to test to an array and use some and isNaN:
ValidInput = (a, b, c) => ![a,b,c].some(isNaN);
For example:
ValidInput = (a, b, c) => ![a, b, c].some(isNaN);
if (!ValidInput(1, "a", 3)) {
console.log('Invalid input data');
}
Upvotes: 0
Reputation: 2394
You could write your valdiator-function like this:
function ValidInput(a, b, c) {
var argArr = Array.from(arguments);
return !argArr.some(isNaN);
}
Upvotes: 2
Reputation: 35202
Use isNaN
const a_number = parseFloat(prompt("Please, enter a-number", '0'));
const b_number = parseFloat(prompt("Please, enter b-number", '0'));
const c_number = parseFloat(prompt("Please, enter c-number", '0'));
console.log(a_number, b_number, c_number);
ValidInput(a_number, b_number, c_number);
function ValidInput (a, b, c) {
if (isNaN(a) || isNaN(b) || isNaN(c)) {
console.log('Invalid input data');
} else {
// do something
}
}
Mind you, your code works even if you enter something which starts with a number and then has some non-numeric characters. For Example, if you type 5.5somethingelse
, parseFloat
takes the numbers until it hits a non-numeric value. It gets 5.5
Upvotes: 1
Reputation: 3850
May use is isNaN
or typeof
function:
function ValidInput (a, b, c) {
if (isNaN(a) || isNaN(b) || isNaN(c)) {
console.log('Invalid input data');
} else {
return
}
}
Upvotes: 3