Apply Validations Using KnokcoutJS in ASP.Net Application - Part 2

Introduction

In my previous article I told you How to Apply Validations Using KnokcoutJS in ASP.NET Application - Part 1.

In today's article I will tell you how to apply validations using KnokcoutJS in an ASP.NET Application - Part 2.

This article shows how to use the Knockout Extenders Property to apply the validations using KnokcoutJS in an ASP.NET Application.

Step 1

First of all you need to add an external Knockout js file into your application, you can either download it from this link: "KnockoutJS" or can download my application that is available at the start of this article in Zip Format and then can use the file attached with this Zip file.

After downloading the file you need to call it in the head section of your application.

<head runat="server">

    <title></title>

    <script src="knockout-2.3.0.js"></script>

</head>

Step 2

Now we can work on our application. First we will work on the ViewModel. To do that you need to Add a Script tag under the Body Section and then add this code:

        <script>

            ko.extenders.required = function (Name, otherMessage) {

 

                Name.hasError = ko.observable();

                Name.showMessage = ko.observable();

 

                function validate(newValue) {

                    Name.hasError(newValue ? false : true);

                    Name.showMessage(newValue ? "" : otherMessage || "Please Enter Something");

                }

 

                validate(Name());

 

                Name.subscribe(validate);

 

                return Name;

            };

 

            function x(first, last) {

                this.initialName = ko.observable(first).extend({ required: "Please enter first name" });

                this.surName = ko.observable(last).extend({ required: "" });

            }

 

            ko.applyBindings(new x("Anubhav""Chaudhary"));

        </script>

Here in the start I had used the extenders, in these extenders I created a function in which the "Name" and "otherMessage"  arguments are passed. The first argument is the Observable itself.

In this function I had created two Observables named hasError and showMessage.

Then one more function is created in which an argument newValue is used. This function will work every time a user enters a new value, if the new value is found to be null, in other words if no value is entered, then an error message will be shown.

Validate(Name()); will initialize the Validation.

Name.subscribe(validate) will validate whenever the value will be changed.

return Name will return the original Observable.

Then a function is created named "x()". In this function two Observables are created on which validation is to be applied. The extender created in the preceding function will be called using the extend function of Observable. I used this extend function in both of the Observables so both should show the same error message but you can see that I had passed an error message in the required of the first Observable but the second Observable doesn't have an error message so the first one will show the error message provided with itself but the second one will show the message that was provided in the extender property.

Step 3

Until now our work on the ViewModel is completed so we can proceed and can work on the View of our application.

Write this code in the View of your application:

    <div>

    <p>

    <input data-bind='value: initialName, valueUpdate: "afterkeydown"' />

    <span data-bind='visible: initialName.hasError, text: initialName.showMessage'> </span>

</p>

<p>

    <input data-bind='value: surName, valueUpdate: "afterkeydown"' />

    <span data-bind='visible: surName.hasError, text: surName.showMessage'> </span>

</p>

    </div>

Here I took two TextBoxes and two Labels. The TextBox will contain the value inserted form the User and the Label will be used to show the error message.

The first TextBox is bound to the initialName and the second TextBox is bound to the surName.

After that both the Labels are bound to the Observable and their Extender checks the value and shows the error message.

The complete code of this application is as follows:

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

    <script src="knockout-2.3.0.js"></script>

</head>

<body>

    <form id="form1" runat="server">

    <div>

    <p>

    <input data-bind='value: initialName, valueUpdate: "afterkeydown"' />

    <span data-bind='visible: initialName.hasError, text: initialName.showMessage'> </span>

</p>

<p>

    <input data-bind='value: surName, valueUpdate: "afterkeydown"' />

    <span data-bind='visible: surName.hasError, text: surName.showMessage'> </span>

</p>

    </div>

        <script>

            ko.extenders.required = function (Name, otherMessage) {

                //add some sub-observables to our observable

                Name.hasError = ko.observable();

                Name.showMessage = ko.observable();

 

                //define a function to do validation

                function validate(newValue) {

                    Name.hasError(newValue ? false : true);

                    Name.showMessage(newValue ? "" : otherMessage || "Please Enter Something");

                }

 

                //initial validation

                validate(Name());

 

                //validate whenever the value changes

                Name.subscribe(validate);

 

                //return the original observable

                return Name;

            };

 

            function x(first, last) {

                this.initialName = ko.observable(first).extend({ required: "Please enter first name" });

                this.surName = ko.observable(last).extend({ required: "" });

            }

 

            ko.applyBindings(new x("Anubhav""Chaudhary"));

        </script>

    </form>

</body>

</html>

Output

On debugging the application you will get output as in the following:

knockout validation

But as I remove the first Name then an error will be shown like this one :

knockout validation

If I remove both the Names then you will see that various error messages are shown as in the first Observable we had passed an error message with it but in the second Observable we didn't pass any type of message so it's showing the message that was declared in the Extenders.

knockout validation

Up Next
    Ebook Download
    View all
    Learn
    View all