Knockout JS Validation using an AJAX Callback Result

Knockout JS Validation using an AJAX Callback Result

Phill Luby
2nd April 2012

Home Insights Knockout JS Validation using an AJAX Callback Result

I was looking for an easy way to implement a validation based on the result of an AJAX request without making it synchronous. I noticed that Knockout JS Validation wraps it’s calls to validation functions in a computed observable. This means our validation result will be dynamically re-evaluated if we base it on another observable.

The trick is to create an observable into which we feed the result of the HTTP call-back, and use that in the validation function. Here’s a code snippet using JQuery too, it assumes there’s a service that checks that the field value is unique and returns true or false.

var viewModel = {
    myField: ko.observable(null),
    isMyFieldUnique: ko.observable(true)
};

viewModel.myField.subscribe(function () {
    $.getJSON(
        'myservice?myField=' + escape(viewModel.myField(),
        function (result) {
            viewModel.isMyFieldUnique(result);
        }
    );
});

viewModel.myField.extend({
    validation: {
        validator: function (val, param) { 
            return viewModel.isMyFieldUnique();
        },
        message: "myField is not unique."
    }
});
Share Article

Insights.

NewRedo Co-founder Royd Brayshay Nominated for Agile Award
NewRedo Co-founder Royd Brayshay Nominated for Agile Award

NewRedo Co-founder Royd Brayshay has been nominated in the Best Agile Coach category of the 2012 UK Agile Awards. The objective of the UK Agile Awards is to recognise the People, Projects and Products that have contributed to the success… 

Discover More
Setting up AWS SSO with Google Workspace
Setting up AWS SSO with Google Workspace

I recently configured Single Sign On (SSO) from our Google accounts to AWS. AWS SSO is the recommended way to configure SSO across multiple AWS accounts, yet Google is not a supported identity provider. However, this simply meant that there… 

Discover More
Moving to a better address
Moving to a better address

Discover More