Search code examples
knockout-2.0knockout-validation

Knockout.js - Forcing input to be numeric - allow dot and comma notation


To better understand, pls go to http://knockoutjs.com/documentation/extenders.html and have a look at Live Example 1: Forcing input to be numeric

I can enter a decimal value with a . (dot) but not with a comma. Then the amount jumps to 0.

Any idea how I can allow dot AND comma? I would like to allow input like 20.00 and 20,00

Kind regards,

K.


Solution

  • You could implement a small fix in the numeric extender (ref. the extenders documentation page that you posted) to solve this. In the "write" method of the extender, add the following code on top:

            if (typeof newValue == "string") {
                newValue = newValue.replace(",", ".");
            }
    

    The if-statement is needed to prevent an error on model initialization. When the model is first created, the value is most likely set to a number instead of a string, so we can't call the .replace method on this object.