验证数字if语句JavaScript
我有下面的语句,我只想验证用户没有将字段留空。我的问题是验证数字if语句JavaScript,javascript,Javascript,我有下面的语句,我只想验证用户没有将字段留空。我的问题是productPrice,如果我取消对这三行的注释,它将不起作用,并进入else块,即使我提供的数字符合标准。如果我只对productPrice!=“”它将允许任何字符串作为price的值进入数据库。这里怎么了 if ( productTitle != "" && productPrice != "" && // Number.isInteger
productPrice
,如果我取消对这三行的注释,它将不起作用,并进入else
块,即使我提供的数字符合标准。如果我只对productPrice!=“”
它将允许任何字符串作为price
的值进入数据库。这里怎么了
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");
}
if(
productTitle!“”&&
产品价格!“”&&
//编号:isInteger(产品价格)&&
//产品价格>0&&
//产品价格<1000&&
productDescription!“”
) {
让productData={
标题:productTitle,
价格:产品价格,
description:productDescription,
};
// .....
}否则{
console.log(“需要所有字段”);
}
您可以将productPrice从字符串转换为数字(整数),然后尝试与0和1000进行比较
var pp=parseInt(productPrice)| 0;
如果(
...
!isNan(产品价格)&&
pp>0&&
pp<1000&&
...
){...
在第1行中,我们检查productPrice是否为NaN,以捕获此异常。变量如何可以同时是字符串和数字?您只需删除
productPrice!=“”&&&
并使用其余的注释条件。如果您使用字符串比较和解析,您可以避免不必要的检查。我建议您通过告诉用户如何检查NaN来改进您的答案。不希望他们进行字符串比较:)对于exmaple,isNaN(productPrice)
?