Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#4.0

Validations in knockout js

4.00/5 (2 votes)
17 Jun 2014CPOL10 min read 50.8K  
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<br />
$(document).ready(function () {<br />
    fillCandidate();<br />
});<br />
function fillCandidate() {<br />
    var viewModel = new CandidateViewModel();<br />
    var CandidateData = new CandidateData(0, '', '', '', '', '', '', '', 0, '', 0, '', '', '', '', '', '');<br />
    viewModel.CandidateDetails(CandidateData);<br />
    try {<br />
        // initiate validations<br />
        ko.validation.init({<br />
            registerExtenders: true,<br />
            messagesOnModified: true,<br />
            insertMessages: false<br />
        });<br />
        ko.applyBindings(viewModel, document.getElementById('CandidateDetails'));<br />
    }<br />
    catch (e) { }<br />
}<br />
//Candidate view model for observable models and operations<br />
function CandidateViewModel() {<br />
    var self = this;<br />
    var emptyVal = '';<br />
    self.CandidateDetails = ko.observableArray([]);<br />
    self.CandidateDetail = ko.observable("");<br />
    self.create = function () {     <br />
        self.CandidateDetail().showErrors(true);<br />
        if (self.CandidateDetail().isValid()) {<br />
            // Code for saving Candidate..<br />
        };<br />
    };<br />
};<br />
// Knockout data model for candidate..<br />
function CandidateData(Id, Name, Address, City, PostCode, TelephoneNo, CandidateId, Relationship, Qualification, State, Country, EmailAddress, CreatedBy, CreatedOn, ModifiedBy, ModifiedOn,Skills) {<br />
    var self = this;<br />
    self.Id = ko.observable(Id);<br />
    self.Name = ko.observable(Name).extend({ required: true }); //required field validator<br />
    self.Address = ko.observable(Address);<br />
    self.City = ko.observable(City);<br />
    self.PostCode = ko.observable(PostCode);<br />
    self.TelephoneNo = ko.observable(TelephoneNo).extend({ required: true });<br />
    self.CandidateId = ko.observable(CandidateId);<br />
    self.Relationship = ko.observable(Relationship).extend({ required: true });<br />
    self.Qualification = ko.observable(Qualification);<br />
    self.State = ko.observable(State);<br />
    self.Country = ko.observable(Country);<br />
    self.EmailAddress = ko.observable(EmailAddress).extend({ email: true }); //regular expression validator for email<br />
    self.Skills = ko.observable(Skills);<br />
    self.CreatedBy = ko.observable(CreatedBy);<br />
    self.CreatedOn = ko.observable(CreatedOn);<br />
    self.ModifiedBy = ko.observable(ModifiedBy);<br />
    self.ModifiedOn = ko.observable(ModifiedOn);<br />
    self.showErrors = ko.observable(false);<br />
    self.showerror = function (item) {<br />
        if (!item.isValid() && self.showErrors()) {<br />
            return true;<br />
        }<br />
        else<br />
            return false;<br />
    };<br />
    self.errors = ko.validation.group(self);<br />
};

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:

@{<br />
   Layout = "~/Views/Shared/_Layout.cshtml"; <br />
}<br />
<script src="http://code.jquery.com/jquery-1.7.1.js"></script><br />
<script src="http://knockoutjs.com/downloads/knockout-3.0.0.js"></script><br />
<script src="~/Scripts/knockout.validation.js"></script><br />
<script src="~/Scripts/CandidateDetails.js"></script><br />
<div id="CandidateDetails">   <br />
<h2>Candidate</h2> <br />
    <table><br />
      <tbody><br />
          <tr><br />
              <td>Name<span style="border: 1px solid red;"</td><br />
              <td>  <input data-bind="value: CandidateDetail().Name, css:{'required-field':CandidateDetail().showerror(CandidateDetail().Name)}, valueUpdate: 'afterkeydown'" type="text" title="KDName"   maxlength="50" /></td><br />
              <td>Telephone</td><br />
              <td>  <input data-bind="value: CandidateDetail().TelephoneNo, css:{'required-field':CandidateDetail().showerror(CandidateDetail().TelephoneNo)}, valueUpdate: 'afterkeydown'" type="text" title="KDTNo"   maxlength="15" /></td><br />
          </tr><br />
          <tr><br />
              <td>Relationship</td><br />
              <td> <input data-bind="value: CandidateDetail().Relationship, css:{'required-field':CandidateDetail().showerror(CandidateDetail().Relationship)}, valueUpdate: 'afterkeydown'" type="text" title="KDRelationship"   maxlength="50" /></td><br />
              <td>Email</td><br />
              <td> <input data-bind="value: CandidateDetail().EmailAddress, css:{'required-field':CandidateDetail().showerror(CandidateDetail().EmailAddress)}, valueUpdate: 'afterkeydown'" type="text" title="KDEAddress"   maxlength="50" /></td><br />
          </tr><br />
          <tr><br />
              <td>Qualification</td><br />
              <td>@Html.DropDownList("ddlQualification", (IEnumerable<SelectListItem>)ViewBag.Qualification, "", new { data_bind = "value: CandidateDetail().Qualification" })</td><br />
              <td>Skill Set</td><br />
              <td> <input data-bind="value: CandidateDetail().Skills" type="text" title="KDSkill"  maxlength="100"  /></td><br />
          </tr><br />
          <tr><br />
              <td>Address</td><br />
              <td><input data-bind="value: CandidateDetail().Address" type="text" title="KDAddress"  maxlength="100"  /></td><br />
              <td>Town / City</td><br />
              <td><input data-bind="value: CandidateDetail().City" type="text" title="KDCity"  maxlength="50"  /></td><br />
          </tr><br />
          <tr><br />
              <td>County / State</td><br />
              <td><input data-bind="value: CandidateDetail().State" type="text" title="KDState"   maxlength="50" /></td><br />
              <td>Post Code</td><br />
              <td><input data-bind="value: CandidateDetail().PostCode" type="text" title="KDCode"   maxlength="20" /></td><br />
          </tr><br />
          <tr><br />
              <td>Country</td><br />
              <td>@Html.DropDownList("ddlCountry", (IEnumerable<SelectListItem>)ViewBag.Country, "", new { data_bind = "value: CandidateDetail().Country" })</td><br />
              <td colspan="2"><br />
                  <input id="btnSave" data-bind="event:{click: create}" type="button" class="button" value="Submit" /><br />
              </td><br />
          </tr><br />
      </tbody><br />
    </table>  <br />
    <div><br />
            <table><br />
                <thead><br />
                    <tr id="tableHeader"><br />
                        <th style="display:none;"></th><br />
                        <th><br />
                            Name<br />
                        </th><br />
                        <th class="show-for-large-up"><br />
                            Relationship<br />
                        </th><br />
                        <th><br />
                            Address<br />
                        </th><br />
                        <th class="show-for-large-up"><br />
                            City<br />
                        </th><br />
                        <th><br />
                            State<br />
                        </th><br />
                        <th class="show-for-large-up"><br />
                        Email Address<br />
                            </th>    <br />
                    </tr><br />
                </thead><br />
                <tbody style="cursor: pointer;" data-bind="foreach: CandidateDetails"><br />
                  <tr><br />
                            <td data-bind="text: Id" style="display: none;"></td><br />
                            <td data-bind="text: Name"></td><br />
                            <td data-bind="text: Relationship"></td><br />
                            <td data-bind="text: Address"></td><br />
                            <td data-bind="text: City"></td><br />
                            <td data-bind="text: State"></td><br />
                            <td data-bind="text: EmailAddress"></td>                          <br />
                        </tr><br />
                </tbody><br />
            </table>     <br />
        </div><br />
</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()<br />
        {<br />
            ViewBag.Qualification = GetQualifications();<br />
            ViewBag.Country = Getcountry();<br />
            return View();<br />
        }<br />
        private List<SelectListItem> GetQualifications()<br />
        {<br />
            var data = new List<SelectListItem><br />
            {<br />
                new SelectListItem {Value = "qualification1", Text = "qualification1"},<br />
                new SelectListItem {Value = "qualification2", Text = "qualification2"}<br />
            };<br />
            return data;<br />
        }<br />
        private List<SelectListItem> Getcountry()<br />
        {<br />
            var data = new List<SelectListItem><br />
            {<br />
                new SelectListItem {Value = "country1", Text = "country1"},<br />
                new SelectListItem {Value = "country2", Text = "country2"}<br />
            };<br />
            return data;<br />
        }

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({<br />
            registerExtenders: true,<br />
            messagesOnModified: true,<br />
            insertMessages: false<br />
        });

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)