Introduction

In this article, we will see how we can implement validation rules with knockout.js library. Client-Side validation improves the performance and helps us to validate the data before saving it into the database.
As I mentioned, in this demo, we will show a form with different fields, where we are applying the validation rules. I hope, you will like this.
Let’s start.
Create your Application
Open Visual Studio and select File-> click New Project.
The New Project Window will pop up. Select ASP.NET Web Application (.NET Framework), name your project, and click OK.
Knockout
Now, a new dialog will pop up to select the template. We are going to choose MVC and click OK.
Knockout
Knockout part
First of all, we are installing a knockout.js library. For doing this, right-click on References > Manage NuGet Packages.
Knockout
Now, type Knockout.js in the search text box, select the first line, as shown below, and click the Install button.
Knockout
After installing Knockout.js library from Solution Explorer, make sure that JS files given below have been added, as shown below.
Knockout
Create HTML page
Now, we need to add new HTML page. To do this, right click on Project > Add > HTML page.
Knockout
EmployeeForm.html
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>.: Validation Form :.</title>
  5. <meta charset="utf-8" />
  6. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  7. <meta name="viewport" content="width=device-width, initial-scale=1">
  8. <!--CSS-->
  9. <link href="Content/bootstrap.min.css" rel="stylesheet" />
  10. <style type="text/css">
  11. .errorStyle {
  12. background-color: #ffd800;
  13. color: #808080;
  14. font-size: 13px;
  15. padding: 5px 5px;
  16. border-radius: 5px;
  17. margin-top: 7px;
  18. }
  19. </style>
  20. </head>
  21. <body>
  22. <nav class="navbar navbar-default navbar-fixed-top">
  23. <div class="container-fluid">
  24. <div class="navbar-header">
  25. <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
  26. <span class="sr-only">Toggle navigation</span>
  27. <span class="icon-bar"></span>
  28. <span class="icon-bar"></span>
  29. <span class="icon-bar"></span>
  30. </button>
  31. <a class="navbar-brand" href="#">Validation With KnockOut JS</a>
  32. </div> <!-- END HEADER NAV -->
  33. </div> <!-- END CONTAINER -->
  34. </nav><!-- END NAV-->
  35. <div class="container" style="margin-top: 7%;">
  36. <div class="row">
  37. <div class="col-md-8">
  38. <div class="panel panel-default">
  39. <div class="panel-heading">
  40. <b> Employee Form</b>
  41. </div> <!-- END HEADING-->
  42. <div class="panel-body">
  43. <form>
  44. <div class="form-group">
  45. <label for="FirstName">First Name</label>
  46. <input type="text" id="FirstName" class="form-control" data-bind="value:FirstName" placeholder="First Name" />
  47. </div><!-- END FIRST NAME -->
  48. <div class="form-group">
  49. <label for="LastName">Last Name</label>
  50. <input type="text" id="LastName" class="form-control" data-bind="value:LastName" placeholder="Last Name" />
  51. </div><!-- END Last Name -->
  52. <div class="form-group">
  53. <label for="Email">Email</label>
  54. <input type="text" id="Email" class="form-control" data-bind="value:Email" placeholder="Email" />
  55. </div><!-- END Email -->
  56. <div class="form-group">
  57. <label for="Country">Country</label>
  58. <select class="form-control" data-bind="options: CountryList, value: Country, optionsCaption:'Choose your country ...'"></select>
  59. </div> <!-- END COUNTRY -->
  60. <div class="form-group">
  61. <label for="PhoneNumber">Phone Number</label>
  62. <input type="text" id="PhoneNumber" class="form-control" data-bind="value:PhoneNumber" placeholder="Phone Number" />
  63. </div><!-- END Phone Number -->
  64. <div class="form-group">
  65. <label for="Address">Address</label>
  66. <input type="text" id="Address" class="form-control" data-bind="value:Address" placeholder="Address" />
  67. </div><!-- END Address -->
  68. <div class="form-group">
  69. <label for="Password">Password</label>
  70. <input type="password" id="Password" class="form-control" data-bind="value:Password" placeholder="Password" />
  71. </div><!-- END Password -->
  72. <div class="form-group">
  73. <label for="Password">Confirm Password</label>
  74. <input type="password" id="ConfirmPassword" class="form-control" data-bind="value:ConfirmPassword" placeholder="ConfirmPassword" />
  75. </div><!-- END Confirm Password -->
  76. <div class="form-group">
  77. <label for="captcha">20 + 30</label>
  78. <input type="text" id="captcha" class="form-control" data-bind="value:captcha" placeholder="Captcha" />
  79. </div><!-- END CAPTCHA -->
  80. <button type="button" class="btn btn-success" data-bind="click:submit">
  81. <span class="glyphicon glyphicon glyphicon-floppy-disk" aria-hidden="true"></span> Save
  82. </button>
  83. <button type="button" class="btn btn-info">
  84. <span class="glyphicon glyphicon glyphicon-refresh" aria-hidden="true"></span> Reset
  85. </button>
  86. <div class="alert alert-success" role="alert" style="display:none; margin-top: 10px;"> <span class="glyphicon glyphicon glyphicon-ok-circle" aria-hidden="true"></span> Form has submitted with successful </div>
  87. <div class="alert alert-danger" role="alert" style="display:none; margin-top: 10px;"> <span class="glyphicon glyphicon glyphicon-remove-circle" aria-hidden="true"></span> Please check your submission </div>
  88. </form> <!-- END FORM-->
  89. </div> <!-- END BODY-->
  90. </div> <!-- END PANEL-->
  91. </div> <!-- END COL-MD-8-->
  92. </div> <!-- END ROW-->
  93. </div> <!-- END CONTAINER-->
  94. <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
  95. <script src="Scripts/jquery-1.10.2.min.js"></script>
  96. <!-- Include all compiled plugins (below), or include individual files as needed -->
  97. <script src="Scripts/bootstrap.min.js"></script>
  98. <!--KnockOutJs librairies-->
  99. <script src="Scripts/knockout-2.3.0.js"></script>
  100. <script src="Scripts/knockout.validation.js"></script>
  101. <script type="text/javascript">
  102. $(document).ready(function() {
  103. ko.validation.init({
  104. registerExtenders: true,
  105. messagesOnModified: true,
  106. insertMessages: true,
  107. parseInputAttributes: true,
  108. errorClass: 'errorStyle',
  109. messageTemplate: null
  110. }, true);
  111. // Captcha Function
  112. var captcha = function(val) {
  113. return val == 50;
  114. }
  115. //checkPassword Function
  116. var checkPassword = function(val, other) {
  117. return val == other;
  118. }
  119. var viewModel = {
  120. //var self = this;
  121. FirstName: ko.observable().extend({ required: true, minLength: 2, maxLength: 17 }),
  122. LastName: ko.observable().extend({ required: true, minLength: 2, maxLength: 17 }),
  123. Email: ko.observable().extend({ email: true }),
  124. CountryList: ko.observableArray(['Morocco', 'India', 'USA']),
  125. Country: ko.observable().extend({ required: true }),
  126. PhoneNumber: ko.observable().extend({
  127. required: true,
  128. pattern: {
  129. message: 'Phone Number does not match my pattern',
  130. params: '^06-[0-9]{2}-[0-9]{2}-[0-9]{2}-[0-9]{2}$'
  131. }
  132. }),
  133. Address: ko.observable().extend({ required: true }),
  134. Password: ko.observable().extend({ required: true }),
  135. captcha: ko.observable().extend({
  136. //custom Validation
  137. validation: {
  138. validator: captcha,
  139. message: 'Please check your captcha !!'
  140. }
  141. }),
  142. submit: function() {
  143. $('div.alert-success').hide();
  144. $('div.alert-danger').hide();
  145. if (viewModel.errors().length === 0) {
  146. //alert('Thank you');
  147. $('div.alert-success').show();
  148. } else {
  149. //alert('Please check your submission');
  150. $('div.alert-danger').show();
  151. }
  152. }
  153. };
  154. //Confirm Password
  155. viewModel.ConfirmPassword = ko.observable().extend({
  156. validation: {
  157. validator: checkPassword,
  158. message: 'Please check your password !',
  159. params: viewModel.Password
  160. }
  161. })
  162. //Catch errors
  163. viewModel.errors = ko.validation.group(viewModel);
  164. ko.applyBindings(viewModel);
  165. });
  166. </script>
  167. </body>
  168. </html>
Adding validation to an observable
In order to apply the validation rules, we have used extenders but before we proceed, please make sure that you have added the libraries given below in your HTML page.
  1. <!--KnockOutJs librairies-->
  2. <script src="Scripts/knockout-2.3.0.js"></script>
  3. <script src="Scripts/knockout.validation.js"></script>
As you can see, ko.validation.init({ … }) function must be initialized with the options given below.
CSS code
  1. <style type="text/css">
  2. .errorStyle
  3. {
  4. background-color:#ffd800;
  5. color:#808080;
  6. font-size:13px;
  7. padding:5px 5px;
  8. border-radius:5px;
  9. margin-top:7px;
  10. }
  11. </style>
The next step is that we can validate our model properties by using extend ({….}) function, as shown below.
FirstName property
We want to add an extender, which allows an observable to be marked as required and having minLength: 2 characters and maxLength: 17 characters.
  1. FirstName: ko.observable().extend({ required: true, minLength: 2, maxLength:17})
PhoneNumber property
Adding an extender that allows an observable to be required and Phone Number pattern, as shown below.
  1. PhoneNumber: ko.observable().extend({
  2. required: true,
  3. pattern: {
  4. message: 'Phone Number does not match my pattern',
  5. params: '^06-[0-9]{2}-[0-9]{2}-[0-9]{2}-[0-9]{2}$'
  6. }
  7. })
Captcha property
We want to implement captcha in our Form. To do this, we need to use validation: {…} object, then we are adding two parameters, as given below. ConfirmPassword property
Also, we are using the validation object, which needs the parameters given below.
Output
Now, you can run our demo by pressing F5.
Let’s see the output.
Knockout
Please share your feedback and queries in the comments box.