验证值是否为空或零("0"),但如果为"0.0"则如何验证? [英] validation if value is empty or zero ('0'), but what if it's "0.0"
问题描述
我今天在验证表单时遇到问题.用户必须在价格字段中输入价格.如果他们输入0(出于某种原因)或将其保留为空,那么我的以下代码将捕获此错误:
I encountered a problem today when working on validating a form. The user has to input a price in the price field. If they input 0 (for some reason) or leave it empty, then my following code catches this:
var pricevar = $("#price").val();
if (pricevar == '' || pricevar == '0') {
var errormessage = 'Product Price is empty or zero. Please enter it above.';
$("#errordiv").html(errormessage).slideDown();
return false;
} else {
return false;
}
我的输入字段如下:
<input type="text" name="price" id="price" placeholder="0.00">
但是,如果(再次由于某种原因)用户输入0.00,则不会检测到该值,并且会提交表单.我已经尝试过null
和empty
,但是没有任何作用.有人知道我如何检测到0.00是一个空数字,但0.01(或更大)不是吗?
However, if (again, for some reason) the user enters 0.00 then this isn't detected and the form gets submitted. I have tried null
and empty
but nothing is working. Does anyone know how I detect that 0.00 is an empty number, but that 0.01 (or great) is not?
推荐答案
您可以使用parseFloat()
将变量从字符串转换为浮点数,并且应该可以正常工作.
You can use parseFloat()
to convert your variable from a string to a float, and it should be working.
if (parseFloat(pricevar) == 0) {
// your code
}
这篇关于验证值是否为空或零("0"),但如果为"0.0"则如何验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!