luke_mclachlan
luke_mclachlan

Reputation: 1054

validation if value is empty or zero ('0'), but what if it's "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;
}

My input field is as follows:

<input type="text" name="price" id="price" placeholder="0.00">

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?

Upvotes: 1

Views: 10798

Answers (3)

leedotpang
leedotpang

Reputation: 106

One quick fix you can use is to parse the input value with the JavaScript Number() function and check if it is less than 0 (which would check for zero--and negative numbers).

Is the price invalid if negative? If so:

var pricevar = $("#price").val();
if (pricevar == '' || Number(pricevar) < 0) {
    var errormessage = 'Product Price is empty, negative, or zero. Please enter it above.';
    $("#errordiv").html(errormessage).slideDown();
    return false;
} else {
    return false;
}

If you just want to check if the number is zero, update the second operator in your if statement to

Number(pricevar) == 0

Upvotes: 1

Andy
Andy

Reputation: 5091

You need to coerce your pricevar variable into a number. Multiplying it by one is one way of doing this:

var pricevar = $("#price").val() * 1;
if (pricevar <= 0) {
    console.log('product price is empty');
} else {
    console.log('all good');
}

Upvotes: 0

Dorian
Dorian

Reputation: 211

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
}

Upvotes: 3

Related Questions