KnockoutJS Validations - Without A Plugin And Using A Plugin

Here we are going to see how we can implement some basic validations using KnockoutJS. As we mentioned in the title, we are going to create a validation demo in two ways.

  • Without using any plugin, our own custom way
  • Using an existing plugin, in an easy way

If you are totally new to KnockoutJS, I strongly recommend you  read my previous post where I have shared some basics of KnockoutJS. We will be using Visual Studio for our development.

Now, let’s begin.

Download source code

Background

As I have been working on a project where we use KnockoutJS, it was my duty to implement some validation on an existing page. This article shows the ways I have tried to implement the same - like I said above, using a plugin and without using a plugin. Now, let’s go and implement the same in your application too. Shall we?

Create a HTML page

To work with KnockoutJS, we need a page. Let’s create it first. Before we do that, please do not forget to install KnockoutJS and jQuery from NuGet.


Installing_KnockOut_JS_from_NuGet

  1. <!DOCTYPE html>  
  2. <html>  
  3.   
  4. <head>  
  5.     <title></title>  
  6.     <meta charset="utf-8" /> </head>  
  7.   
  8. <body> </body>  
  9.   
  10. </html>  
Now, create a JS file and include it in your page.
  1. <script src="Validations-Without-Plugin.js"></script>  

Let’s begin our tutorial – KnockoutJS validation without using a plugin

Open your JS file (Validations-Without-Plugin.js) where we are going to write our scripts. As a first step, we need to create our View Model and bind it using applyBindings function.

  1. $(function() {  
  2.     function myViewModel(firstName, lastName, email) {  
  3.         this.txtFirstName = ko.observable(firstName);  
  4.         this.txtLastName = ko.observable(lastName);  
  5.         this.txtEmail = ko.observable(email);  
  6.     };  
  7.     ko.applyBindings(new myViewModel("Sibeesh""Venu""[email protected]"));  
  8. });  
Now, let's create our View.
  1. <!DOCTYPE html>  
  2. <html>  
  3.   
  4. <head>  
  5.     <title>KnockOut JS Validations</title>  
  6.     <meta charset="utf-8" />  
  7.     <script src="Scripts/jquery-3.1.1.min.js"></script>  
  8.     <script src="Scripts/knockout-3.4.1.js"></script>  
  9.     <script src="Scripts/Validations-Without-Plugin.js"></script>  
  10. </head>  
  11.   
  12. <body>  
  13.     <table>  
  14.         <caption>Knockout JS Validation</caption>  
  15.         <tr>  
  16.             <td> First Name: <input type="text" id="txtFirstName" name="txtFirstName" data-bind='value: txtFirstName' /> </td>  
  17.         </tr>  
  18.         <tr>  
  19.             <td> Last Name: <input type="text" id="txtLastName" name="txtLastName" data-bind='value: txtLastName' /> </td>  
  20.         </tr>  
  21.         <tr>  
  22.             <td> Email: <input type="text" id="txtEmail" name="txtEmail" data-bind='value: txtEmail' /> </td>  
  23.         </tr>  
  24.         <tr>  
  25.             <td> <input type="button" value="Submit" /> </td>  
  26.         </tr>  
  27.     </table>  
  28. </body>  
  29.   
  30. </html>  
If you run your page, you can see that the View has got tenupdated with the values we have given in our View Model (Do you remember the use of observable() ? )


Knockout_JS_Observables_Updated

So far, everything is good. Now, it is time to update our View Model and create some extenders.

KnockoutJS extenders are the easy way to give some additional functionalities to your observables. It can be anything and in this case, we are to create some validations for our observables or our controls.

We can create the extenders and update the View as preceding.

  1. $(function() {  
  2.     ko.extenders.isRequired = function(elm, customMessage) {  
  3.         //add some sub-observables to our observable  
  4.         elm.hasError = ko.observable();  
  5.         elm.message = ko.observable();  
  6.         //This is the function to validate the value entered in the text boxes  
  7.         function validateValueEntered(valEntered) {  
  8.             elm.hasError(valEntered ? false : true);  
  9.             //If the custom message is not given, the default one is taken  
  10.             elm.message(valEntered ? "" : customMessage || "I am required");  
  11.         }  
  12.         //Call the validation function for the initial validation  
  13.         validateValueEntered(elm());  
  14.         //Validate the value whenever there is a change in value  
  15.         elm.subscribe(validateValueEntered);  
  16.         return elm;  
  17.     };  
  18.     ko.extenders.isEmail = function(elm, customMessage) {  
  19.         //add some sub-observables to our observable  
  20.         elm.hasError = ko.observable();  
  21.         elm.message = ko.observable();  
  22.         //This is the function to validate the value entered in the text boxes  
  23.         function validateEmail(valEntered) {  
  24.             var emailPattern = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;  
  25.             //If the value entered is a valid mail id, return fals or return true  
  26.             elm.hasError((emailPattern.test(valEntered) === false) ? true : false);  
  27.             //If not a valid mail id, return custom message  
  28.             elm.message((emailPattern.test(valEntered) === true) ? "" : customMessage);  
  29.         }  
  30.         //Call the validation function for the initial validation  
  31.         validateEmail(elm());  
  32.         //Validate the value whenever there is a change in value  
  33.         elm.subscribe(validateEmail);  
  34.         return elm;  
  35.     };  
  36.   
  37.     function myViewModel(firstName, lastName, email) {  
  38.         this.txtFirstName = ko.observable(firstName).extend({  
  39.             isRequired: "You missed First Name"  
  40.         });  
  41.         this.txtLastName = ko.observable(lastName).extend({  
  42.             isRequired: ""  
  43.         });  
  44.         this.txtEmail = ko.observable(email).extend({  
  45.             isEmail: "Not a valid mail id"  
  46.         });  
  47.     };  
  48.     ko.applyBindings(new myViewModel("Sibeesh""Venu""[email protected]"));  
  49. });  
Here, .extend({ isRequired: “You missed First Name” }); is used for calling the extenders we have just created. The first parameter is the extender name you are creating, and the second one is just a custom message. I have explained the codes with comments, If you get any issues or doubt, please feel free to ask your queries. Now, it is time to update our View.
  1. <!DOCTYPE html>  
  2. <html>  
  3.   
  4. <head>  
  5.     <title>KnockOut JS Validations</title>  
  6.     <meta charset="utf-8" />  
  7.     <script src="Scripts/jquery-3.1.1.min.js"></script>  
  8.     <script src="Scripts/knockout-3.4.1.js"></script>  
  9.     <script src="Scripts/Validations-Without-Plugin.js"></script>  
  10.     <style>  
  11.         .error {  
  12.             color: #D8000C;  
  13.             background-color: #FFBABA;  
  14.             font-family: cursive;  
  15.         }  
  16.           
  17.         table {  
  18.             border: 1px solid #c71585;  
  19.             padding: 20px;  
  20.         }  
  21.           
  22.         td {  
  23.             border: 1px solid #ccc;  
  24.             padding: 20px;  
  25.         }  
  26.     </style>  
  27. </head>  
  28.   
  29. <body>  
  30.     <table>  
  31.         <caption>Knockout JS Validation</caption>  
  32.         <tr>  
  33.             <td> First Name: <input type="text" id="txtFirstName" name="txtFirstName" data-bind='value: txtFirstName, valueUpdate: "afterkeydown"' /> <span class="error" data-bind='visible: txtFirstName.hasError, text: txtFirstName.message'></span> </td>  
  34.         </tr>  
  35.         <tr>  
  36.             <td> Last Name: <input type="text" id="txtLastName" name="txtLastName" data-bind='value: txtLastName, valueUpdate: "afterkeydown"' /> <span class="error" data-bind='visible: txtLastName.hasError, text: txtLastName.message'></span> </td>  
  37.         </tr>  
  38.         <tr>  
  39.             <td> Email: <input type="text" id="txtEmail" name="txtEmail" data-bind='value: txtEmail, valueUpdate: "afterkeydown"' /> <span class="error" data-bind='visible: txtEmail.hasError, text: txtEmail.message'></span> </td>  
  40.         </tr>  
  41.         <tr>  
  42.             <td> <input type="button" value="Submit" /> </td>  
  43.         </tr>  
  44.     </table>  
  45. </body>  
  46.   
  47. </html>  
Every observable will be having its own hasError and message properties. And have you noticed that we are usig valueUpdate: “afterkeydown” in each data-bind event of our control ? This is for initiating the validation. Now, let’s run our application and see whether it is working fine or not.

Knockout JS validation without a plugin demo

Knockout JS validation using a plugin - The easy way

As we are going to use a plugin, we need to install it from the NuGet first. You can always get the plugin from here.


Knockout_Validation_JS_from_NuGet

Can we create our View Model now?

  1. $(function() {  
  2.     function myViewModel(firstName, lastName, email) {  
  3.         this.txtFirstName = ko.observable(firstName).extend({  
  4.             required: true  
  5.         });  
  6.         this.txtLastName = ko.observable(lastName).extend({  
  7.             required: false  
  8.         });  
  9.         this.txtEmail = ko.observable(email).extend({  
  10.             email: true  
  11.         });  
  12.     };  
  13.     ko.applyBindings(new myViewModel("Sibeesh""Venu""[email protected]"));  
  14. });  
You can see that there are only a few lines of code when compared to the old one. Now, we can create our View.
  1. <!DOCTYPE html>  
  2. <html>  
  3.   
  4. <head>  
  5.     <title>KnockOut JS Validations</title>  
  6.     <meta charset="utf-8" />  
  7.     <script src="Scripts/jquery-3.1.1.min.js"></script>  
  8.     <script src="Scripts/knockout-3.4.1.js"></script>  
  9.     <script src="Scripts/knockout.validation.js"></script>  
  10.     <script src="Scripts/Validations-Plugin.js"></script>  
  11.     <style>  
  12.         table {  
  13.             border: 1px solid #c71585;  
  14.             padding: 20px;  
  15.         }  
  16.           
  17.         td {  
  18.             border: 1px solid #ccc;  
  19.             padding: 20px;  
  20.         }  
  21.     </style>  
  22. </head>  
  23.   
  24. <body>  
  25.     <table>  
  26.         <caption>Knockout JS Validation</caption>  
  27.         <tr>  
  28.             <td> First Name: <input type="text" id="txtFirstName" name="txtFirstName" data-bind='value: txtFirstName' /> </td>  
  29.         </tr>  
  30.         <tr>  
  31.             <td> Last Name: <input type="text" id="txtLastName" name="txtLastName" data-bind='value: txtLastName' /> </td>  
  32.         </tr>  
  33.         <tr>  
  34.             <td> Email: <input type="text" id="txtEmail" name="txtEmail" data-bind='value: txtEmail' /> </td>  
  35.         </tr>  
  36.         <tr>  
  37.             <td> <input type="button" value="Submit" /> </td>  
  38.         </tr>  
  39.     </table>  
  40. </body>  
  41.   
  42. </html>  
Please don’t forget to include the knockout.validation.js in your page. If everything is ready, run your application and see the output.


Knockout JS validation with plugin demo

That’s all for today. You can always download the source code attached to see the complete code and application. Happy coding!.

References

See also

Conclusion

Did I miss anything that you think was needed? Did you find this post useful? Please share with me your valuable suggestions and feedback. Please see this article in my blog here.

Your turn. 

A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, ASP.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.


Similar Articles