1

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?

luke_mclachlan
  • 1,035
  • 1
  • 15
  • 35

3 Answers3

3

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
}
Dorian
  • 211
  • 2
  • 5
  • Thanks Dorian. All three answers work nicely if the user enters numeric characters, but if I entered 0.00a then all but yours failed the validation check. This has also been detailed here http://stackoverflow.com/a/11988751/3842368, so thanks for your answer it appears to be the best one. – luke_mclachlan Jul 22 '15 at 15:52
1

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
leedotpang
  • 106
  • 1
  • 7
  • Dorians answer appears to be the best but thank you for highlighting the fact that I failed to take into account negative numbers. Upvote for that. – luke_mclachlan Jul 22 '15 at 15:53
0

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');
}
Andy
  • 4,901
  • 5
  • 35
  • 57