0

I must prevent the user to insert a non-numeric value in an input type text with knockout:

Here my HTML:

<input data-bind="value: myModel.myNumber, valueUpdate: 'afterkeydown', event: { change: validateMyNumber }" type="number" />

Here the js:

self.validateMyNumber = function (data, event) {
     var input = data.myModel.myNumber();
      if (input == "")
      {

      }
};

I can't find some logic to write inside the validateMyNumber function... when I press the button, it it is not a number I lost the old value in my model and I get an empty string... in the textBox nothing changes instead... I just want that if I insert a non-numeric value I must block the insert in the textbox... How can I do?

royhowie
  • 11,075
  • 14
  • 50
  • 67
Simone
  • 2,304
  • 6
  • 30
  • 79

1 Answers1

2

I use this as a global rule for input[type=number] elements. You don't need anything specific to knockout.

$(document).on('keypress change focus', 'input[type="number"]', function (e) {
    var isKeypress = e.type === 'keypress';
    var isChange = e.type === 'change';
    var isFocus = e.type === 'focus' || e.type === 'focusin';
    var charTyped = String.fromCharCode(e.which);
    var $el = $(this);

    // store original value to revert change that invalidates min
    if (isFocus) {
        this.originalVal = $el.val();
        return;
    }

    // block invalid keystrokes
    if (isKeypress) {
        // don't allow non-numeric chars
        if (!/^[\.0-9]$/.test(charTyped)) {
            e.preventDefault();
            return;
        }

        // don't allow double periods (123.456.789)
        if (charTyped === '.' && $el.val().indexOf('.') > -1) {
            e.preventDefault();
            return;
        }
    }

    // don't allow >max or <min values
    if (isChange) {
        var min = $el.attr('min');
        var max = $el.attr('max');
        var amt = parseInt($el.val() + charTyped);

        if (max && amt > max || min && amt < min) {
            // revert change
            $el.val(this.originalVal);
            $el.focus();
        }
    }
});
caseyWebb
  • 1,997
  • 17
  • 18
  • I had already tried to use jQuery but unsuccessfully... I don't know why but I never enter inside that function – Simone Apr 29 '15 at 13:38
  • With this code, if you set a breakpoint is it hit when you enter something? – caseyWebb Apr 29 '15 at 13:49
  • no :( never.. I think is knockout that prevent to enter in this code – Simone Apr 30 '15 at 08:36
  • 1
    I use this exact snippet with Knockout, so I'm not sure what's going on unless it's not in document.ready. You could also write a custom binding for this; don't have time right now but I'll try to get an example by the end of the day. – caseyWebb Apr 30 '15 at 12:49
  • Thanx... I wrote a custom bindings... It worked for me... – Simone Apr 30 '15 at 13:52
  • `String.fromCharCode(e.which)` ! - that's a piece of gold! Why I didn't know this method?! – Roman Bekkiev Aug 04 '15 at 12:05