Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decimal is not validated correctly in MVC 3 with jQuery Validator

I have a property like so public decimal? MyProperty { get; set; }, it IS NOT required and IS nullable, but if I don't put a value > 0 the validator say that the field MyProperty must be a number, if I leave the field empty I receive the same error, and if I put a 0 (zero) I receive the same error.

Ex:
0 -> Error
1 -> Ok
0,00 -> Error
0,01 -> Ok
empty -> Error

I don't understand why this don't work, I'm using $.preferCulture("pt-BR"); but don't make sense, because the value 0,01 is accepted, than I don't believe that culture can be the problem.

PS: The validation don't work in client side, the server side work correctly.

like image 954
Cesar Avatar asked Mar 11 '11 17:03

Cesar


1 Answers

Default number function has a bug. It test's parseFloat(value) == 0 and parseFloat for '0' returns 0.

To solve this, I have overwritten it as

$.validator.methods.number = function (value, element) {
  return parseFloat(value).toString() !== "NaN";
}

I know that isn't the best way, but this workaround solves my problem.

like image 185
Zote Avatar answered Oct 04 '22 14:10

Zote