Kendo UI jQuery Validator

Introduction and Background

 
Basically, based on my experience, client-side validation is one form of protection to protect data before being stored at the backend. In addition, client-side validation gives the user the user-experience needed to validate the required and/or invalid data to be submitted. Many would ask why there are many client-side validation libraries. To answer that, I think most web projects have different needs and requirements, that’s one main reason why we see  that so many of these libraries exists. Here are some of the popular validation libraries: jQuery validation-pluginparsley, quick-validation.js, and Validatr just to name a few.
 
Client-side validation is very popular for many developers. Thus, it is one form of validation and many would argue that you also need server-side validation. We won’t be discussing server-side validation but just remember that both are important.
 
Now, getting back to the client-side will be focusing on the usage of Kendo UI jQuery validator. Thus, in this article, we are going to tackle the following subjects:
  • What is jQuery UI Kendo Validator?
  • Quick basic example using built-in rules
  • How to change error template, validate on-blur event and clear error messages?
  • How to know when the validation of the form completes?
  • jQuery UI Kendo Validator Rules & Messages

    • Default rules and using custom message using data-rule-msg
    • Custom rules and custom messages

Project Setup and Prerequisites

 
I used the CDNs, used by Telerik UI Dojo. See the Kendo UI for jQuery CDNs below.
  1. <!-- add the at least required css-->    
  2. <!-- start of Kendo UI jQuery related CSS-->    
  3. <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2020.1.219/styles/kendo.common.min.css">    
  4. <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2020.1.219/styles/kendo.rtl.min.css">    
  5. <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2020.1.219/styles/kendo.default.min.css">    
  6. <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2020.1.219/styles/kendo.mobile.all.min.css">    
  7. <!-- end of Kendo UI Jquery related CSS-->    
  8.     
  9. <!-- add the kendo ui library-->    
  10. <!-- start of Kendo UI jQuery Scripts-->    
  11. <script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>    
  12. <script src="https://kendo.cdn.telerik.com/2020.1.219/js/jszip.min.js"></script>    
  13. <script src="https://kendo.cdn.telerik.com/2020.1.219/js/kendo.all.min.js"></script>    
  14. <!-- end of Kendo UI jQuery Scripts-->    
See the project structure below.
 
Kendo UI jQuery Validator
 

What is jQuery UI Kendo Validator?

  • jQuery UI Kendo validator is a widget that provides an easy way to do client-side form validation for developers by developers.
  • This widget-validator is built around the HTML5 form validation attributes such as required, min and max, pattern and type.
  • It provides a convenient way to use the default or built-in validation rules and also gives you the ability to set up a custom rule and message handling.

Quick basic example using built-in rules

 
For us to get started, let's look at the  example below on how to simply use the Kendo UI jQuery validator. 
  1. <form id="basicUsage" method="post">      
  2.     <h3>Quick basic example using default rules</h3>      
  3.     <div>      
  4.         <label>Firstname:</label>      
  5.         <input type="text" name="firstname" id="firstname" placeholder="Put your firstname" required />      
  6.     </div>      
  7.     <div>      
  8.         <label>Lastname:</label>      
  9.         <input type="text" name="lastname" id="lastname" placeholder="Put your lastname" required />      
  10.     </div>      
  11.     <div>      
  12.         <label>Email:</label>      
  13.         <input type="email" name="email" id="email" placeholder="Put your email" required />      
  14.     </div>      
  15.     <div id="message">      
  16.       
  17.     </div>      
  18.     <div>      
  19.         <button type="submit">Submit</button>      
  20.     </div>      
  21. </form>       
  1. var form = $("#basicUsage"),    
  2.     messageDiv = $("#message"),    
  3.     validator = null;    
  4.     
  5. $(function () {    
  6.     
  7.     if (form) {    
  8.         //need to attach the form to kendo validator and get reference    
  9.         validator = form.kendoValidator().data("kendoValidator");     
  10.     }    
  11. });    
  12.     
  13. $(form).submit(validateMyForm);    
  14.     
  15. function validateMyForm(e) {    
  16.     
  17.     e.preventDefault();    
  18.     
  19.     if (validator) {    
  20.     
  21.         var resultOfValidation = validator.validate();    
  22.     
  23.         if (!resultOfValidation) {    
  24.             messageDiv.html("Please fill up the fields properly");    
  25.         } else {    
  26.             messageDiv.html("");    
  27.         }    
  28.     }    
  29. }    
Here are some points I would like to explain about the example above. 
  • The HTML example above uses the HTML 5 validation attributes which works fine with Kendo validator. 
  • The form that was attached to the Kendo validator for you to validate the form by invoking the method validate
  • Just remember that these HTML 5 validation attributes are being collected by Kendo validator in order to provide user-side validation. 
I know this is just a quick basic example. Thus, we are covering more in the other sections of this article. See the output below. 
 
Output
 
Kendo UI jQuery Validator
 

How to change error template, validate on-blur event and clear error messages?

 
Now, that we have seen a quick basic example. We are going to intensify things a bit, by configuring the Kendo validator to use a different error-template, give the user the capability to clear the error-messages and validate the HTML input controls on-blur event.
  1. <form id="basicUsage" method="post">      
  2.     <h3>Set a new  error template And configure on-blur event</h3>      
  3.     <div>      
  4.         <label>Firstname:</label>      
  5.         <input type="text" name="firstname" id="firstname" placeholder="Put your firstname" required />      
  6.     </div>      
  7.     <div>      
  8.         <label>Lastname:</label>      
  9.         <input type="text" name="lastname" id="lastname" placeholder="Put your lastname" required />      
  10.     </div>      
  11.     <div>      
  12.         <label>Email:</label>      
  13.         <input type="email" name="email" id="email" placeholder="Put your email" required />      
  14.     </div>      
  15.     <div id="message">      
  16.       
  17.     </div>      
  18.     <div>      
  19.         <button type="submit">Submit</button>      
  20.         <button type="reset" id="reset">Clear</button>      
  21.     </div>      
  22. </form>       
  1. var form = $("#basicUsage"),    
  2.     messageDiv = $("#message"),    
  3.     clearBtn = $("#reset"),    
  4.     validator = null,    
  5.     //Setup my the look and feel for the errors on the page.    
  6.     myErrorTemplate    
  7.         = '<span class="k-widget k-tooltip k-tooltip-validation custom_validationSection">' +    
  8.                         '<span class="k-icon k-i-error"></span > Hello #=message#</span > ';    
  9.     
  10. $(function () {    
  11.     
  12.     if (form) {    
  13.         //configure the kendoValidator    
  14.         validator =form.kendoValidator({    
  15.             validateOnBlure: true//validate on blur event    
  16.             errorTemplate: myErrorTemplate //set the new error template    
  17.         }).data("kendoValidator");    
  18.     }    
  19.                 
  20. });    
  21.     
  22. $(form).submit(validateMyForm);    
  23.     
  24. $(clearBtn).click(hideFormErrorMessages);    
  25.     
  26. function validateMyForm(e) {    
  27.     
  28.     e.preventDefault();    
  29.     
  30.     if (validator) {    
  31.     
  32.         var resultOfValidation = validator.validate();    
  33.     
  34.         if (!resultOfValidation) {    
  35.             messageDiv.html("Please fill up the fields properly");    
  36.         } else {    
  37.             messageDiv.html("");    
  38.         }    
  39.     }    
  40. }    
  41.     
  42. function hideFormErrorMessages() {    
  43.     
  44.     if (validator) {    
  45.     
  46.         validator.hideMessages(); //gives the user the capability to clear error messages!    
  47.         messageDiv.html("");    
  48.     }    
  49. }     
Output
 
Effect on how we have changed the error-template. 
 
Kendo UI jQuery Validator 
Effect on setting the on-blur event to true.
 
Kendo UI jQuery Validator
 

How to know when the validation of the form completes?

 
We haven't gone so far yet. We have more examples to show. Now, we already know almost all of the basic configurations needed to deal with the Kendo validator widget. Haven't you wondered what event-method will trigger when the validation of the form completes? In this example, that is what we are going to show. 
 
But before that, I would like to point out that we are going to use the validate event-handler function because this is triggered when the validation of the form is complete. So let us see this in action below.
  1. <form id="basicUsage">      
  2.     <h3>ValidatioFormCompletes</h3>      
  3.     <div>      
  4.         <label>Firstname:</label>      
  5.         <input type="text" name="firstname" id="firstname" placeholder="Put your firstname" required />      
  6.     </div>      
  7.     <div>      
  8.         <label>Lastname:</label>      
  9.         <input type="text" name="lastname" id="lastname" placeholder="Put your lastname" required />      
  10.     </div>      
  11.     <div>      
  12.         <label>Email:</label>      
  13.         <input type="email" name="email" id="email" placeholder="Put your email" required />      
  14.     </div>      
  15.     <div id="message">      
  16.       
  17.     </div>      
  18.     <div>      
  19.         <button type="submit">Submit</button>      
  20.         <button type="reset" id="reset">Clear</button>      
  21.     </div>      
  22. </form>     
  1. var form = $("#basicUsage"),    
  2.     messageDiv = $("#message"),    
  3.     clearBtn = $("#reset"),    
  4.     validator = null,    
  5.     myErrorTemplate = '<span class="k-widget k-tooltip k-tooltip-validation custom_validationSection">' +    
  6.                                     '<span class="k-icon k-i-error"></span >Hello #=message#</span >';    
  7.     
  8. $(function () {    
  9.     
  10.     if (form) {    
  11.     
  12.         validator = form.kendoValidator({    
  13.             validateOnBlur: true,    
  14.             errorTemplate: myErrorTemplate,    
  15.             validate: function (e) { //this is triggered when the validation is complete    
  16.                 if (e.valid === true) {    
  17.     
  18.                     toggleControls();    
  19.                     toggleErrorSummary();    
  20.     
  21.                     kendo.ui.progress(form, true);    
  22.     
  23.                     setTimeout(function () {    
  24.                         kendo.ui.progress(form, false);    
  25.                         toggleControls();    
  26.                         kendo.alert("Your registration was succesful!");    
  27.                         $(clearBtn).trigger("click");    
  28.                     }, 500);    
  29.     
  30.                 }    
  31.                 else {    
  32.                     toggleErrorSummary(true);    
  33.                 }    
  34.     
  35.                 return false;    
  36.             }    
  37.         }).data("kendoValidator");    
  38.     }    
  39. });    
  40.     
  41. $(clearBtn).click(hideFormErrorMessages);    
  42.     
  43. $(form).submit(function () {    
  44.     return false;    
  45. });    
  46.     
  47. function hideFormErrorMessages() {    
  48.     
  49.     if (validator) {    
  50.         toggleErrorSummary();    
  51.         validator.hideMessages();    
  52.     }    
  53. }    
  54.     
  55. function toggleErrorSummary(show) {    
  56.     
  57.     if (show === true) {    
  58.         messageDiv.html("Please fill up the fields properly");    
  59.     
  60.     } else {    
  61.         messageDiv.html("");    
  62.     }    
  63. }    
  64.     
  65. function toggleControls() {    
  66.     
  67.     if (form.find("input, button").attr("disabled")) {    
  68.         form.find("input, button").attr("disabled"false);    
  69.     } else {    
  70.         form.find("input, button").attr("disabled"true);    
  71.     }    
  72. }     
Output
 
Kendo UI jQuery Validator
 

jQuery UI Kendo Validator Rules & Messages

 
Custom Message Attributes Complete List 
 
Before going deeper to the Kendo validator custom rules and custom messages, I would like to show the complete attributes that can be used for the custom message. 
 
 Custom Message Attribute  Description
 data-[rule]-msg  Where [rule] is the failing validation rule. This gives you the ability to be precise and specific to your error messages. 
 validationMessage  If you don't have a complex validation message per rule. This is the way to go and easy. 
 title  title
 
Just remember that these attributes will be checked first before applying the messages within the Kendo validation widget configuration.
 

Default rules and using custom message using data-rule-msg

 
Now, we are going to see the usage of the default rules with the combination of custom-message using the data-[rule]-msg. I know that we have tackled the built-in/default rules as the first example of this article and let us combine them together with a custom message. With Kendo validator widget we have the opportunity to create our own custom messages. But before that, I listed it down so we can have an easy reference. 
 
 Default/Built-in Rules  Custom Attribute Example usage 
 required  data-required-msg  <input type="text" required data-required-msg="This is required"/>
 pattern  data-pattern-msg  <input type="text" data-pattern-msg="Invalid characters"/>
 step  data-step-msg  <input type="number" step="2" data-step-msg="By twos only"/>
 min  data-min-msg  <input type="number" min="1" data-min-msg="Need to start at one"/>
 max  data-max-msg  <input type="number" min="1" max="10" data-max-msg="Up to 10 ony"/>
 url  data-url-msg  <input type="url" data-url-msg="Invalid url"/>
 number  data-number-msg  <input type="number" data-number-msg="Numbers only/>
 email  data-email-msg  <input type="email" data-email-msg="Invalid email"/>
 date  data-date-msg  <input type="date" data-date-msg="Invalid date"/>
 
Let us see this in action. 
  1. <form id="basicUsage" method="post">      
  2.     <h3>DefaultRulesWithCustomMessage</h3>      
  3.     <div>      
  4.         <label>Firstname:</label>      
  5.         <input type="text" name="firstname" id="firstname" placeholder="Put your firstname" required       
  6.                data-required-msg="Your firstname is required! :-)" />      
  7.     </div>      
  8.     <div>      
  9.         <label>Lastname:</label>      
  10.         <input type="text" name="lastname" id="lastname" placeholder="Put your lastname" required       
  11.                data-required-msg="Your lastname is required! :-)"/>      
  12.     </div>      
  13.     <div>      
  14.         <label>BirthDate:</label>      
  15.         <input type="date" name="birthdate" id="birthdate" placeholder="Your birthdate" required       
  16.                data-date-msg="Your birthdate is not recognized! :-)"/>      
  17.     </div>      
  18.     <div>      
  19.         <label>Email:</label>      
  20.         <input type="email" name="email" id="email" placeholder="Put your email" required       
  21.                data-required-msg="Your email is required! :-)"       
  22.                data-email-msg="Your email is not recognized!"/>      
  23.     </div>      
  24.     <div>      
  25.         <label>Country Code:</label>      
  26.         <input type="text" name="countryCode" id="countryCode" placeholder="Your country code" pattern="[A-Za-z]{3}"      
  27.                required      
  28.                data-required-msg="Country code is required! :-)"      
  29.                data-pattern-msg="Unable to recognize your country code!"/>      
  30.     </div>      
  31.     <div>      
  32.         <label>Number of Mobile Phones to donate:</label>      
  33.         <input type="number" id="mobilephonetodonate" name="mobilephonetodonate" step="2" min="2" max="10 required"      
  34.                data-step-msg="Steps should be divisble by 2"      
  35.                data-min-msg="Minimum of 2 should be donated"      
  36.                data-max-msg="Maximum of 10 only"/>      
  37.     </div>      
  38.     <div>      
  39.         <label>Your favorite search engine?</label>      
  40.         <input type="url" name="url" id="url" placeholder="Your favorite search engine" required      
  41.                data-required-msg="Search engine is required!"      
  42.                data-url-msg="Unable to recognize the URL you have given!"/>      
  43.     </div>      
  44.     <div id="message">      
  45.       
  46.     </div>      
  47.     <div>      
  48.         <button type="submit">Submit</button>      
  49.     </div>      
  50. </form>       
  1. var form = $("#basicUsage"),    
  2.     messageDiv = $("#message"),    
  3.     validator = null;    
  4.     
  5. $(function () {    
  6.     
  7.     if (form) {    
  8.     
  9.                     // attach a validator to the container and get a reference    
  10.         validator = form.kendoValidator().data("kendoValidator");    
  11.         console.log(validator);    
  12.     }    
  13. });    
  14.     
  15. $(form).submit(validateMyForm);    
  16.     
  17. function validateMyForm(e) {    
  18.     
  19.     e.preventDefault();    
  20.     
  21.     if (validator) {    
  22.     
  23.         var resultOfValidation = validator.validate();    
  24.     
  25.         if (!resultOfValidation) {    
  26.             messageDiv.html("Please fill up the fields properly");    
  27.         } else {    
  28.             messageDiv.html("");    
  29.         }    
  30.     }    
  31. }     
Output
 
Kendo UI jQuery Validator
 

Custom rules and custom messages

 
This our last section of this article. In this section, we are going to show an example, how to create custom rules and custom messages. If you are not a fan of these custom message validation attributes, you can still configure Kendo validator for your own needs. See the example below. 
  1. <form id="basicUsage" method="post">    
  2.     <h3>CustomRulesWithCustomMessageUsingValidationAttribute</h3>    
  3.     <div>    
  4.         <label>Username:</label>    
  5.         <input type="text" name="username" id="username" placeholder="Put your firstname"     
  6.                             data-message="Username is undoubtedly required!"    
  7.                             data-messageUsername="Username already exists"/>    
  8.     </div>    
  9.     <div>    
  10.         <label>Email:</label>    
  11.         <input type="email" name="myEmail" id="myEmail" placeholder="Put your email"     
  12.                 data-message="Email is undoubtedly required!" />    
  13.     </div>    
  14.     <div>    
  15.         <label>Country Code:</label>    
  16.         <input type="text" name="countryCode" id="countryCode" placeholder="Your country code"    
  17.                 data-message="Country-code is undoubtedly required!"    
  18.                 />    
  19.     </div>    
  20.     <div id="message">    
  21.     
  22.     </div>    
  23.     <div>    
  24.         <button type="submit">Submit</button>    
  25.     </div>    
  26. </form>     
  1. var form = $("#basicUsage"),  
  2.     messageDiv = $("#message"),  
  3.     validator = null;  
  4.   
  5. $(function () {  
  6.   
  7.     if (form) {  
  8.         validator = form.kendoValidator({  
  9.             rules: {  
  10.                 customRequired: function (input) {  
  11.                     return ($.trim(input.val()) !== "");  
  12.                 },  
  13.                 customEmail: function (input) {  
  14.   
  15.                     var emailFormat = /^\w+([\.-]?\w+)*@@\w+([\.-]?\w+)*(\.\w{2,3})+$/;  
  16.   
  17.                     if ($.trim(input.val()) !== "" & input.is("[name='myEmail']")) {  
  18.                         return input.val().match(emailFormat);  
  19.                     }  
  20.   
  21.                     return true;  
  22.                 },  
  23.                 usernameExists: function (input) {  
  24.                     if (input.is("[name='username']")) {  
  25.                         var result = true;  
  26.                         $.ajax({  
  27.                             url: `CheckUserName?username=${input.val()}`,  
  28.                             async: false,  
  29.                             success: function (response) {  
  30.   
  31.                                 result = response;  
  32.                             }  
  33.                         });  
  34.   
  35.                         return result;  
  36.                     }  
  37.   
  38.                     return true;  
  39.                 }  
  40.             },  
  41.             messages: {  
  42.                 customRequired: function (input) {  
  43.   
  44.                     return input.data("message");  
  45.                 },  
  46.                 usernameExists: function (input) {  
  47.                     console.log("usernameExists");  
  48.                     if (input.is("[name='username']")) {  
  49.                         return input.attr("data-messageUsername");  
  50.                     }  
  51.                 },  
  52.                 customEmail: "Invalid email!" // an example of validation messages defined as custom messages  
  53.             }  
  54.         }).data("kendoValidator");  
  55.     }  
  56. });  
  57.   
  58. $(form).submit(validateMyForm);  
  59.   
  60. function validateMyForm(e) {  
  61.   
  62.     e.preventDefault();  
  63.   
  64.     if (validator) {  
  65.   
  66.         var resultofvalidation = validator.validate();  
  67.   
  68.         if (!resultofvalidation) {  
  69.             messageDiv.html("please fill up the fields properly");  
  70.         } else {  
  71.             messageDiv.html("");  
  72.         }  
  73.     }  
  74. }  
At last, you have been through a lot of examples. But before we end, I would like to point out that it is important to always return true after your custom-rule method, especially if it is very specific for one HTML control because based on the behavior of Kendo validator, it tries to validate every input within the form. Therefore, specificity is needed in your validation.
 

Summary

 
In this article, we have discussed the following,
  • What is jQuery UI Kendo Validator?
  • Quick basic example using built-in rules
  • How to change error template, validate on-blur event and clear error messages
  • How to know when the validation of the form completes
  • jQuery UI Kendo Validator Rules & Messages

    • Default rules and using custom message using data-rule-msg
    • Custom rules and custom messages
I hope you have enjoyed this article, as I have enjoyed writing it. You can also find the sample code here at GitHub. Until next time, happy programming! Kendo UI jQuery Validator