Click here to Skip to main content
Click here to Skip to main content

Use Ajax Validation in Knockout

, 3 Jul 2014
Rate this:
Please Sign up or sign in to vote.

Introduction

In knockout we can use custom validation to validate your view models. But some time we may need to examine validation from server end. Here we will demonstrate how we can use Knockout validation with jquery  ajax and server end calling.

Background

For quick preview check out http://jsfiddle.net/FkxKK/

To perform this example we are using libraries like,

- jquery-2.1.1.js

- knockout-3.1.0.js

- knockout.validation.js

- jquery.mockjax.js     to mock our ajax calls, which is an exciting library to use for ajax mocking.

Using the code

First we will use a custom validation rule with index 'userNameUsed' like this.

- val indicates the value binded from the html DOM, and otherValue what value we expected to be.

- $.when ensures synchs ajax call, and waits inside the scope until the ajax call is finished.

- IsUsed is returned from the server, indicating if the used name is already used or not (or compare to you preferred returned object or its property.)

/*Validations*/
ko.validation.rules['userNameUsed'] = {
    //val form binded value from html, otherVale what we wanted tobe
    validator: function (val, otherVal) {       
        var isUsed;
        var json = JSON.stringify({ userName: val });
        $.when(
            $.ajax({
                url: '/validation/IsUserNameUsed',
                dataType: "json",
                type: "POST",
                contentType: 'application/json; charset=utf-8',
                data: json,
                async: false,
            })
        ).then(function (data, textStatus, jqXhr) {
           isUsed = (textStatus === 'success') ? data.IsUsed : null;
        });
        return isUsed === otherVal;         //if false error message would be shown
    },
    message: 'This user name is already in use'
};
ko.validation.registerExtenders();

Use this validation rule into our view model like this, with other validation rules

/*fields*/
self.userName = ko.observable('').extend({ required: true, userNameUsed: false });

as we have assigned userNameUsed: false in the view model, means we are expecting result is to be false

- if validator ajax calls data.IsUsed returns false, no error message would be shown

- if ajax call fails or data.IsUsed returned true, error message would be shown

 

We will find two test cases at Scripts/mock.validationPage.js to mimic our ajax call as we are not using any real server. Uncomment at list a one to test if the validation is working or not.

It would be better if we use ajax validations after basic validations like required, min, max ... etc.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

diponsust

Bangladesh Bangladesh
No Biography provided

Comments and Discussions

 
QuestionMy 5 PinmemberGovindaraj Rangaraj4-Jul-14 2:42 
AnswerRe: My 5 Pinmemberdiponsust4-Jul-14 2:50 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140721.1 | Last Updated 4 Jul 2014
Article Copyright 2014 by diponsust
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid