Click here to Skip to main content
11,428,281 members (52,627 online)
Click here to Skip to main content

Validations in knockout js

, 17 Jun 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
Implement validations in knockout js

Introduction

This article explains that how to implement validations using knockout js in asp.net mvc.

Background

To understand this article basic knowledge of following is necessary:

1. Asp.net MVC

2. Knockout JS

Using the code

I am mentioning the steps here to implement validation using knockout js:

1. Create an Asp.net MVC project.

2. Create an Action Result in Home Controller named as Candidate and generate a Candidate View.

3. Create a script file named as Candidate.js

4. Add scripts in candidate view as below:

<script src="http://code.jquery.com/jquery-1.7.1.js"></script>

<script src="http://knockoutjs.com/downloads/knockout-3.0.0.js"></script>

<script src="~/Scripts/knockout.validation.js"></script>(this script can be added by installing a nuget package 'Knockout.Validation').

<script src="~/Scripts/CandidateDetails.js"></script>

Prepare CandidateDetails.js under scripts folder as below:

//ready function

$(document).ready(function () {

    fillCandidate();

});

function fillCandidate() {

    var viewModel = new CandidateViewModel();

    var CandidateData = new CandidateData(0, '', '', '', '', '', '', '', 0, '', 0, '', '', '', '', '', '');

    viewModel.CandidateDetails(CandidateData);

    try {

        // initiate validations

        ko.validation.init({

            registerExtenders: true,

            messagesOnModified: true,

            insertMessages: false

        });

        ko.applyBindings(viewModel, document.getElementById('CandidateDetails'));

    }

    catch (e) { }

}

//Candidate view model for observable models and operations

function CandidateViewModel() {

    var self = this;

    var emptyVal = '';

    self.CandidateDetails = ko.observableArray([]);

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

    self.create = function () {     

        self.CandidateDetail().showErrors(true);

        if (self.CandidateDetail().isValid()) {

            // Code for saving Candidate..

        };

    };

};

// Knockout data model for candidate..

function CandidateData(Id, Name, Address, City, PostCode, TelephoneNo, CandidateId, Relationship, Qualification, State, Country, EmailAddress, CreatedBy, CreatedOn, ModifiedBy, ModifiedOn,Skills) {

    var self = this;

    self.Id = ko.observable(Id);

    self.Name = ko.observable(Name).extend({ required: true }); //required field validator

    self.Address = ko.observable(Address);

    self.City = ko.observable(City);

    self.PostCode = ko.observable(PostCode);

    self.TelephoneNo = ko.observable(TelephoneNo).extend({ required: true });

    self.CandidateId = ko.observable(CandidateId);

    self.Relationship = ko.observable(Relationship).extend({ required: true });

    self.Qualification = ko.observable(Qualification);

    self.State = ko.observable(State);

    self.Country = ko.observable(Country);

    self.EmailAddress = ko.observable(EmailAddress).extend({ email: true }); //regular expression validator for email

    self.Skills = ko.observable(Skills);

    self.CreatedBy = ko.observable(CreatedBy);

    self.CreatedOn = ko.observable(CreatedOn);

    self.ModifiedBy = ko.observable(ModifiedBy);

    self.ModifiedOn = ko.observable(ModifiedOn);

    self.showErrors = ko.observable(false);

    self.showerror = function (item) {

        if (!item.isValid() && self.showErrors()) {

            return true;

        }

        else

            return false;

    };

    self.errors = ko.validation.group(self);

};

The HTML MVC View for candidate with knockout bindings and validations are as below. One can create this view with below steps:

1. Create Candidate Controller by right click on Controller folder and select Add > Controller with template MVC Controller and empty read/write.

2. Right click on Index Action Result in Candidate Controller and select Add View followed by click on Add button in opening popup.

3. Replace the HTML of the Index View with below HTML:

@{

   Layout = "~/Views/Shared/_Layout.cshtml"; 

}

<script src="http://code.jquery.com/jquery-1.7.1.js"></script>

<script src="http://knockoutjs.com/downloads/knockout-3.0.0.js"></script>

<script src="~/Scripts/knockout.validation.js"></script>

<script src="~/Scripts/CandidateDetails.js"></script>

<div id="CandidateDetails">   

<h2>Candidate</h2> 

    <table>

      <tbody>

          <tr>

              <td>Name<span style="border: 1px solid red;"</td>

              <td>  <input data-bind="value: CandidateDetail().Name, css:{'required-field':CandidateDetail().showerror(CandidateDetail().Name)}, valueUpdate: 'afterkeydown'" type="text" title="KDName"   maxlength="50" /></td>

              <td>Telephone</td>

              <td>  <input data-bind="value: CandidateDetail().TelephoneNo, css:{'required-field':CandidateDetail().showerror(CandidateDetail().TelephoneNo)}, valueUpdate: 'afterkeydown'" type="text" title="KDTNo"   maxlength="15" /></td>

          </tr>

          <tr>

              <td>Relationship</td>

              <td> <input data-bind="value: CandidateDetail().Relationship, css:{'required-field':CandidateDetail().showerror(CandidateDetail().Relationship)}, valueUpdate: 'afterkeydown'" type="text" title="KDRelationship"   maxlength="50" /></td>

              <td>Email</td>

              <td> <input data-bind="value: CandidateDetail().EmailAddress, css:{'required-field':CandidateDetail().showerror(CandidateDetail().EmailAddress)}, valueUpdate: 'afterkeydown'" type="text" title="KDEAddress"   maxlength="50" /></td>

          </tr>

          <tr>

              <td>Qualification</td>

              <td>@Html.DropDownList("ddlQualification", (IEnumerable<SelectListItem>)ViewBag.Qualification, "", new { data_bind = "value: CandidateDetail().Qualification" })</td>

              <td>Skill Set</td>

              <td> <input data-bind="value: CandidateDetail().Skills" type="text" title="KDSkill"  maxlength="100"  /></td>

          </tr>

          <tr>

              <td>Address</td>

              <td><input data-bind="value: CandidateDetail().Address" type="text" title="KDAddress"  maxlength="100"  /></td>

              <td>Town / City</td>

              <td><input data-bind="value: CandidateDetail().City" type="text" title="KDCity"  maxlength="50"  /></td>

          </tr>

          <tr>

              <td>County / State</td>

              <td><input data-bind="value: CandidateDetail().State" type="text" title="KDState"   maxlength="50" /></td>

              <td>Post Code</td>

              <td><input data-bind="value: CandidateDetail().PostCode" type="text" title="KDCode"   maxlength="20" /></td>

          </tr>

          <tr>

              <td>Country</td>

              <td>@Html.DropDownList("ddlCountry", (IEnumerable<SelectListItem>)ViewBag.Country, "", new { data_bind = "value: CandidateDetail().Country" })</td>

              <td colspan="2">

                  <input id="btnSave" data-bind="event:{click: create}" type="button" class="button" value="Submit" />

              </td>

          </tr>

      </tbody>

    </table>  

    <div>

            <table>

                <thead>

                    <tr id="tableHeader">

                        <th style="display:none;"></th>

                        <th>

                            Name

                        </th>

                        <th class="show-for-large-up">

                            Relationship

                        </th>

                        <th>

                            Address

                        </th>

                        <th class="show-for-large-up">

                            City

                        </th>

                        <th>

                            State

                        </th>

                        <th class="show-for-large-up">

                        Email Address

                            </th>    

                    </tr>

                </thead>

                <tbody style="cursor: pointer;" data-bind="foreach: CandidateDetails">

                  <tr>

                            <td data-bind="text: Id" style="display: none;"></td>

                            <td data-bind="text: Name"></td>

                            <td data-bind="text: Relationship"></td>

                            <td data-bind="text: Address"></td>

                            <td data-bind="text: City"></td>

                            <td data-bind="text: State"></td>

                            <td data-bind="text: EmailAddress"></td>                          

                        </tr>

                </tbody>

            </table>     

        </div>

</div>

Replace the Index ActionResult in Candidate Controller with the below code of Index() method and add two methods below named as GetQualifications() and Getcountry():

 public ActionResult Index()

        {

            ViewBag.Qualification = GetQualifications();

            ViewBag.Country = Getcountry();

            return View();

        }

        private List<SelectListItem> GetQualifications()

        {

            var data = new List<SelectListItem>

            {

                new SelectListItem {Value = "qualification1", Text = "qualification1"},

                new SelectListItem {Value = "qualification2", Text = "qualification2"}

            };

            return data;

        }

        private List<SelectListItem> Getcountry()

        {

            var data = new List<SelectListItem>

            {

                new SelectListItem {Value = "country1", Text = "country1"},

                new SelectListItem {Value = "country2", Text = "country2"}

            };

            return data;

        }

To understand the working of knockout validation please go through the below explanation for input field:

<input data-bind="value: CandidateDetail().Name, css:{'required-field':CandidateDetail().showerror(CandidateDetail().Name)}, valueUpdate: 'afterkeydown'" type="text" title="KDName"   maxlength="50" />

here data-bind represent knockout binding for value of input field and for adding a css class to input field if candidate name is not entered, value represent the knockout bindings for the value for input field, css represents the css class name(1st parameter) to be applied on input field if condition(2nd parameter) becomes true.

Here we are checking that particular observable variable is valid or not as knockout validations defied on it in js model as per below code:

self.Name = ko.observable(Name).extend({ required: true });
 

Knockout validations are initializing by writing below code in js file before writing applyBindings:

 ko.validation.init({

            registerExtenders: true,

            messagesOnModified: true,

            insertMessages: false

        });

Points of Interest

Knockout js, jquery, MVC..

License

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

Share

About the Author

ashish_5437
Software Developer (Senior)
India India
Developing projects and web applications for more than 6 years.

Comments and Discussions

 
QuestionI need help Pin
aathimuthu26-Jan-15 17:55
memberaathimuthu26-Jan-15 17:55 
AnswerRe: I need help Pin
ashish_543726-Jan-15 21:32
memberashish_543726-Jan-15 21:32 
GeneralRe: I need help Pin
aathimuthu27-Jan-15 22:08
memberaathimuthu27-Jan-15 22:08 
GeneralRe: I need help [modified] Pin
ashish_543728-Jan-15 0:18
memberashish_543728-Jan-15 0:18 
GeneralRe: I need help Pin
aathimuthu3-Feb-15 18:02
memberaathimuthu3-Feb-15 18:02 
QuestionGetting error Pin
Member 90226043-Jan-15 20:06
memberMember 90226043-Jan-15 20:06 
AnswerRe: Getting error Pin
ashish_54374-Jan-15 4:27
memberashish_54374-Jan-15 4:27 

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 | Terms of Use | Mobile
Web04 | 2.8.150428.2 | Last Updated 18 Jun 2014
Article Copyright 2014 by ashish_5437
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid