Using Knockout custom binding utilizing input mask disables Knockout Validation

2.1k views Asked by At

I'd like to use both Knockout Validation and Knockout custom bindings with input masks (http://robinherbots.github.io/jquery.inputmask/). Example: money input box, I don't want the user to be able to enter any alphabetic characters at all in the first place, and I also want to limit the minimum and maximum amount at the same time.

In my JSFiddle you can see that those observables which are not custom bound have a working validation, but the others don't.

http://jsfiddle.net/csabatoth/LkqTU/24841/

<div>
    <p>Title 1: <input data-bind='value: title1' /></p> 
    <p>Amount 1: <input data-bind='value: amount1' /></p> 
    <p>Title 2: <input data-bind='inputmask: { value: title2, mask: "*****" }' /></p> 
    <p>Amount 2: <input data-bind='inputmask: { value: amount2, mask: "money" }' /></p>
</div>

ko.bindingHandlers.inputmask =
{
    init: function (element, valueAccessor, allBindingsAccessor) {
        var mask = valueAccessor();
        var observable = mask.value;

        if (ko.isObservable(observable)) {
            $(element).on('focusout change', function () {
                if ($(element).inputmask('isComplete')) {
                    observable($(element).val());
                } else {
                    observable(null);
                }
            });
        }

        if (mask.mask === "money") {
            $(element).inputmask('decimal',
                                 {
                                     'alias': 'numeric',
                                     'groupSeparator': ',',
                                     'autoGroup': true,
                                     'digits': 2,
                                     'radixPoint': ".",
                                     'digitsOptional': false,
                                     'allowMinus': false,
                                     'prefix': '$ ',
                                     'placeholder': '0'
                                 }
                                );
        } else {
            if (mask.regex)
                $(element).inputmask('Regex', { regex: mask.mask });
            else
                $(element).inputmask(mask.mask);
        }
    },
    update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
        var mask = valueAccessor();
        var observable = mask.value;

        if (ko.isObservable(observable)) {
            var valuetoWrite = observable();
            $(element).val(valuetoWrite);
        }
    }
};

var ViewModel = function() {
    var self = this;

    self.convertMoneyToFloat = function (moneyVal) {
        var value = parseFloat(moneyVal.replace(/[^\.\d]/g, ""));
        return value;
    }

    self.title1 = ko.observable("T1").extend({ maxLength: 5 });
    self.title1.subscribe(function (newValue) {
        console.log("AJAX write T1 " + newValue);
    });
    self.amount1 = ko.observable(110.0).extend({ number: true, min: 10.0, max: 10000.0 });
    self.amount1.subscribe(function (newValue) {
        console.log("AJAX write A1 " + newValue);
    });
    self.title2 = ko.observable("T2").extend({ maxLength: 5 });
    self.title2.subscribe(function (newValue) {
        console.log("AJAX write T2 " + newValue);
    });
    self.amount2 = ko.observable(110.0).extend({ number: true, min: 10.0, max: 10000.0 });
    self.amount2.subscribe(function (newValue) {
        console.log("AJAX write A1 " + self.convertMoneyToFloat(newValue));
    });
};

ko.applyBindings(new ViewModel());
1

There are 1 answers

0
Sam Arustamyan On BEST ANSWER

The validation works just fine as you can see in this fiddle: http://jsfiddle.net/L5ndbnba/2/.

The problem is that the message is not displayed automatically for the masked fields, so you should display the validation message explicitly by adding <span data-bind="validationMessage: amount2"></span>.

Now, since the masked value is stored in amount2, you need to apply your validation rules to the numeric computable to make them work correctly:

self.amount2 = ko.observable(110.0);

self.amount2Numeric = ko.computed(function() {
    return self.convertMoneyToFloat(self.amount2());
});

self.amount2Numeric.extend({ number: true, min: 10.0, max: 10000.0 });

Here is the complete working fiddle: http://jsfiddle.net/L5ndbnba/3/