1

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');
    }
}
2

4 Answers 4

3

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
    }
  }
Sign up to request clarification or add additional context in comments.

2 Comments

isNaN(null) returns false . which is incorrect in case of number. use typeof a ==="number" instead
for this usecase we wont get null since parseFloat(null) = NaN
2

You could write your valdiator-function like this:

function ValidInput(a, b, c) {
    var argArr = Array.from(arguments);
    return !argArr.some(isNaN);
}

Comments

1

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

Comments

0

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');
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.