user12051965
user12051965

Reputation: 147

Validate number if statement JavaScript

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

Upvotes: 2

Views: 172

Answers (1)

LoukasPap
LoukasPap

Reputation: 1381

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.

Upvotes: 1

Related Questions