0

I'm testing some client-side validation on my site and I've run into a bit of a snag.

var budget = document.forms["jobSubmit"]["currency-field"].value; 
var price = budget.replace("$", "");


if (Number(price) >= 9999) {
    alert("Budgets have a maximum of 9999 US dollars.");
    return false;
} else {
alert(price);   
}

return false;

When I try to do a simple greater than condition on my price field, it doesn't return the proper result.

So in this situation, despite that I put in 11111, the greater than isn't working.

enter image description here

However, if I were to switch it to < 10, for example, it'll work just fine and all numbers under 10 will trigger the condition.

Why is this happening?

3
  • Try some basic debugging. Number(11,111) is 11 Commented Dec 30, 2017 at 3:53
  • 2
    In your picture there's a comma in the middle of 11,111.00 which is an invalid number. You will need to remove the commas or else Number("11,111.00") will return NaN. Commented Dec 30, 2017 at 3:53
  • Ah, right. Figured it was something simple like that. Thanks. Commented Dec 30, 2017 at 3:56

1 Answer 1

1

Try the following:

var budget = "$111,111" 
var price = budget.replace("$", "").replace(',','');


if (Number(price) >= 9999) {
    alert("Budgets have a maximum of 9999 US dollars.");
    //return false;
} else {
  alert(price);   
}

Sign up to request clarification or add additional context in comments.

4 Comments

If you don't mind a dependency, the library "numeral.js" handles parsing of formatted numbers very well.
@cadmium, that might be but that is OP's concern whether to use such library or not.
Or remove all invalid characters at once: budget.replace(/[^0-9.]/g, "")
@4castle, yes we can do that. But I think , is allowed in amount. If other invalid characters are present we should consider that as invalid input...thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.