2

I have the following statement where I just want to validate that user does not leave fields empty. My problem is at productPrice, if I uncomment those three lines, it will not work and get into else block even if the number I provide meets the criteria. If I leave it so only with productPrice != "" it will allow any string as value for price into the database. What is wrong here?

if (
    productTitle != "" &&
    productPrice != "" &&
    // Number.isInteger(productPrice) &&
    // productPrice > 0 &&
    // productPrice < 1000 &&
    productDescription != ""
) {
    let productData = {
        title: productTitle,
        price: productPrice,
        description: productDescription,
    };

    // .....
} else {
    console.log("All fields required");
}
3
  • 5
    how can a variable be a string and a number at the same time? Commented Jul 11, 2020 at 10:50
  • You can just remove productPrice != "" && and use the rest of the commented conditions. Commented Jul 11, 2020 at 10:51
  • You can avoid unnecessary checks like string comparison and parsing if you use an <input type="number" /> Commented Jul 11, 2020 at 11:20

1 Answer 1

1

You can convert productPrice from String, to Number(Integer), and then try compare with 0 & 1000.

var pp = parseInt(productPrice) || 0;

if(
 ...
 !isNan(productPrice) &&
 pp > 0 &&
 pp < 1000 &&
 ...
){...

In the 1st line, we check if productPrice is NaN, so as to catch this exception.

Sign up to request clarification or add additional context in comments.

2 Comments

I suggest you improve your answer by telling the user how to check for NaN. Don't want them to do a string comparison :)
For exmaple, isNaN(productPrice)?

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.