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.

Sponsoring the Legal Tech in Leeds’ Hackathon
Sponsoring the Legal Tech in Leeds’ Hackathon

This is why NewRedo are so proud to have sponsored Legal Tech in Leeds Hackathon

Discover More
Taking a look at Dagger
Taking a look at Dagger

Solomon Hykes is probably most famous for being the founder and former CTO of Docker. Docker revolutionised the way we package, run and distribute server applications, so when Hykes starts a new venture, it's worth checking out.

Discover More
Running Terraform in a Lambda Function
Running Terraform in a Lambda Function

I recently set up a Terraform project which I wanted to run on a regular schedule. There are a number of ways to achieve this, but I decided to package the project as a Lambda function and schedule it with… 

Discover More