Click here to Skip to main content
15,868,340 members
Articles / Web Development / HTML
Tip/Trick

Use Ajax Validation in Knockout

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
3 Jul 2014CPOL1 min read 15.9K   126   6   2
How to use Ajax validation in Knockout

Introduction

In Knockout, we can use custom validation to validate our view models. But sometimes, 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 a 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 otherVal 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 compared to your preferred returned object or its property.)
    JavaScript
    /*Validations*/
    ko.validation.rules['userNameUsed'] = {
        //val form binded value from HTML, otherVal what we wanted to be
        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:

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

    as we have assigned userNameUsed: false in the view model, means we are expecting the 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 least 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)


Written By
Bangladesh Bangladesh
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionMy 5 Pin
Govindaraj Rangaraj4-Jul-14 2:42
Govindaraj Rangaraj4-Jul-14 2:42 
AnswerRe: My 5 Pin
DiponRoy4-Jul-14 2:50
mvaDiponRoy4-Jul-14 2:50 

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

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