Apply Knockout Validations in MVC Application

Introduction

The complete code of this application can be downloaded from here.

In my previous article I told you How to Apply CRUD Operations in MVC Application.

This article explains how to apply Knockout Validations in a MVC Application.

Knockout provides a very simple way to apply validations on Observables that can be used in various bindings. Various types of validations are available in Knockout, such as for emails, required validation, minimum value, maximum value and so on.

Use the following procedure to create a sample for this type of application.

Step 1

I am working on the same application on which I had worked on in my previous application, you can download that application from this location: CRUD Operations in MVC Application.

I will work on the Product class that is available in the Views Folder.

What I will do is apply some validations on some Observable and enable the button only when all the validations are fulfilled.

For applying the validations you first need to add some external files to your application as in the following:

  1. Knockout.Validations.js
  2. Knockout.Validations.Debug.js

You can also add their Nugets by typing this single line code in the "Package Manager Console" that will be found under the "Library Package Manager" option of Tool:

PM> Install-Package Knockout.Validation

Step 2

We have now fetched the files necessary for Knockout Validations. Now you need to configure these validations, for that you need to write this code in the ProductViewModel() function:

            ko.validation.rules.pattern.message = 'Invalid.';

 

            ko.validation.configure({

                registerExtenders: true,

                messagesOnModified: true,

                insertMessages: true,

                parseInputAttributes: true,

                messageTemplate: null

            });

This code will configure the validations so that you can use them easily.

Now I will apply the validations on one of the Observable, I will apply four validation on this Observable so that all type of validations can be shown to you.

            var self = this;

            self.Id = ko.observable("");

            self.Title = ko.observable("").extend({ required: true, minLength: 2, maxLength: 40, email: true });

            self.Cost = ko.observable("");

            self.Class = ko.observable("");

You can see that four Observables are declared here but only on the second observable validations are applied, for applying the validations you need to use the extend function.

In the extend function I have declared four validations that will work as follows:

  1. required: true: this will ensure that the user can't leave this Observable empty.
  2. minLength: 2: this will check that the user has entered the given number of text in the Observable.
  3. maxLength: 40: this will check that the user can't enter more values than provided.
  4. email: true: this will check that the user has entered a valid Email Address.

Step 3

Now I will use a TextBox to which the Title() will be bound.

        <div>

            <label>Email:-</label>

            <input id="txt2" data-bind="value: Title, valueUpdate: 'keyup'" title="Title" type="text" />

        </div>

This TextBox will update the ViewModel each time the key will be up.

Then I took a button as in the following:

            <button id="btn1" data-bind="enable:Title.isValid">Check</button>

This button will be disabled if the Title has any type of validation on it, but if the correct value is inserted or you can say if the Title becomes Valid then the Button will become valid and then it can be clicked.

On the button click I will show a Message through JavaScript.

                $('#btn1').click(function () {

                    alert("Welcome");

                    $('#btn1').attr('disabled''disabled');

                });

If the button is clicked then an alert message will be shown and the Button will again become Disabled, but if the user again makes changes in the TextBox where the Title is bound then this Button will again become enabled.

The complete code of this application can be downloaded from here.

Output

On running the application you will get output like this:

knockout validation in MVC1.jpg

Now If I enter a value then the validation will be activated. I have entered a single letter so it has began to show that at least two values are required.

knockout validation in MVC2.jpg

If I enter more then two then the next validation will be activated and it will start showing that a valid Email has not been entered.

knockout validation in MVC3.jpg

As I enter the correct Email Id, all the validations will be removed and the button will be activated.

knockout validation in MVC4.jpg

Now you can click on the button to get the alert message.

knockout validation in MVC5.jpg