简体   繁体   中英

Track change in value of a input in knockout js

In my Knockout.js application I want to validate the user input. I have used custom validation

Below is the code i have used looping through each element in the array.

result.Settings.filter(function (element) {
    element.DisplayMobile = ko.observable(element.PointsForMobile).extend({ required: { message: 'This field cannot be empty' }, useNumberFloatOnly: "abc", maximumValue: 'abc'});
    element.DisplayWeb = ko.observable(element.PointsForWeb).extend({ required: { message: 'This field cannot be empty' }, useNumberFloatOnly: "abc", maximumValue: 'abc'});

    element.Error = ko.observable(false);
});

below is the input in the view

<input type="number" data-bind="value:$data.DisplayWeb,valueUpdate: ['afterkeydown', 'input'],,change:TestValidPoint" class="positiveno" min="0" />
<input type="number" data-bind="value:$data.DisplayMobile,valueUpdate: ['afterkeydown', 'input']" class="positiveno" min="0" />

below is the useNumberFloatOnly validator which works for me.

ko.validation.rules['useNumberFloatOnly'] = {
            validator: function (val, othervalue) {
                var numStr = /^\d*[0-9]\d*$/;

                if (othervalue === "abc") {
                    Settings().filter(function (element) {
                        if (element.DisplayMobile() == "" || element.DisplayWeb() == "") {
                            element.Error(true);

                        }
                        if ((element.DisplayMobile() == val || element.DisplayWeb() == val ) && !numStr.test(val)) {
                            element.Error(true);

                        }
                        else if ((element.DisplayMobile() == val || element.DisplayWeb() == val) && numStr.test(val)) {
                            element.Error(false);
                        }
                    });
                }
                return numStr.test(val);
            },
            message: 'Enter only positive values.Decimals not allowed'
        };

on click of the save button i want to check if any of the fields has any error. two problems i'm facing

1) How to track changes in the input value? what event to use for that? this is for tracking if the input has error and if i can disable the save button .

2) Second thing i tried is on the save button click event on looping through the array the Error observable is always false, even though i'm setting the value as true in the validator.

Please guide

Thanks

You can create a errorGroup for all the observable s for which you want the validation. Then use errorGroup.isValid() to conditionally enable the button

 const viewModel = function() { this.DisplayMobile = ko.observable().extend({ required: true }); this.DisplayWeb = ko.observable().extend({ required: true }); this.submit = function() { if (this.errorGroup.isValid()) { alert('submitted'); } else { this.errorGroup.errors.showAllMessages(); } }; this.errorGroup = ko.validatedObservable({ DisplayMobile: this.DisplayMobile, DisplayWeb: this.DisplayWeb }); }; ko.applyBindings(new viewModel()); 
 .validationMessage{ color:red } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout-validation/2.0.3/knockout.validation.min.js"></script> <fieldset> <legend>Details</legend> <label>Display Mobile: <input data-bind='value: DisplayMobile' /> </label><br> <label>Display Web: <input data-bind='value: DisplayWeb' /> </label> </fieldset> <br> <button type="button" data-bind='click: submit, enable: errorGroup.isValid()'>Submit</button> <br> <br> Error count: <span data-bind='text: errorGroup.errors().length'></span> 

Another similar approach is to use a validation group:

 this.errors = ko.validation.group(this):

 const viewModel = function() { this.DisplayMobile = ko.observable().extend({ required: true }); this.DisplayWeb = ko.observable().extend({ required: true }); this.submit = function() { if (this.errors().length === 0) { alert('submitted'); } else { this.errors.showAllMessages(); } }; this.errors = ko.validation.group(this); }; ko.applyBindings(new viewModel()); 
 .validationMessage{ color:red } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout-validation/2.0.3/knockout.validation.min.js"></script> <fieldset> <legend>Details</legend> <label>Display Mobile: <input data-bind='value: DisplayMobile' /> </label><br> <label>Display Web: <input data-bind='value: DisplayWeb' /> </label> </fieldset> <br> <button type="button" data-bind='click: submit, enable: errors().length === 0'>Submit</button> <br> <br> Error count: <span data-bind='text: errors().length'></span> 

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