简体   繁体   中英

KnockoutJS - filtering user input

I have a simple input text element:

<input type="text" data-bind="value:valInserted,valueUpdate:'afterkeydown'" />

How can I validate the user input on this element? I have a problem with creating the proper binding to port the jQuery code:

$('[id$="pinBox"] :text').keypress(function (e)
{
   if (!(e.charCode >= 48 && e.charCode <= 57) && e.keyCode != 8)
   {
       return false;
   }
});

I think I finally got it.

<input type="text" data-bind="validateValue:valInserted,valueUpdate:'afterkeydown',value:valInserted" />

ko.bindingHandlers.validateValue = {
    update: function (element, valueAccessor, allBindingsAccessor, viewModel)
    {
        var value = ko.utils.unwrapObservable(valueAccessor());
        viewModel.valInserted(value.replace(/[^0-9]/g, ''));
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM