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-plugin,
parsley,
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.
-
-
- <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2020.1.219/styles/kendo.common.min.css">
- <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2020.1.219/styles/kendo.rtl.min.css">
- <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2020.1.219/styles/kendo.default.min.css">
- <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2020.1.219/styles/kendo.mobile.all.min.css">
-
-
-
-
- <script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
- <script src="https://kendo.cdn.telerik.com/2020.1.219/js/jszip.min.js"></script>
- <script src="https://kendo.cdn.telerik.com/2020.1.219/js/kendo.all.min.js"></script>
-
See the project structure below.
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.
- <form id="basicUsage" method="post">
- <h3>Quick basic example using default rules</h3>
- <div>
- <label>Firstname:</label>
- <input type="text" name="firstname" id="firstname" placeholder="Put your firstname" required />
- </div>
- <div>
- <label>Lastname:</label>
- <input type="text" name="lastname" id="lastname" placeholder="Put your lastname" required />
- </div>
- <div>
- <label>Email:</label>
- <input type="email" name="email" id="email" placeholder="Put your email" required />
- </div>
- <div id="message">
-
- </div>
- <div>
- <button type="submit">Submit</button>
- </div>
- </form>
- var form = $("#basicUsage"),
- messageDiv = $("#message"),
- validator = null;
-
- $(function () {
-
- if (form) {
-
- validator = form.kendoValidator().data("kendoValidator");
- }
- });
-
- $(form).submit(validateMyForm);
-
- function validateMyForm(e) {
-
- e.preventDefault();
-
- if (validator) {
-
- var resultOfValidation = validator.validate();
-
- if (!resultOfValidation) {
- messageDiv.html("Please fill up the fields properly");
- } else {
- messageDiv.html("");
- }
- }
- }
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
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.
- <form id="basicUsage" method="post">
- <h3>Set a new error template And configure on-blur event</h3>
- <div>
- <label>Firstname:</label>
- <input type="text" name="firstname" id="firstname" placeholder="Put your firstname" required />
- </div>
- <div>
- <label>Lastname:</label>
- <input type="text" name="lastname" id="lastname" placeholder="Put your lastname" required />
- </div>
- <div>
- <label>Email:</label>
- <input type="email" name="email" id="email" placeholder="Put your email" required />
- </div>
- <div id="message">
-
- </div>
- <div>
- <button type="submit">Submit</button>
- <button type="reset" id="reset">Clear</button>
- </div>
- </form>
- var form = $("#basicUsage"),
- messageDiv = $("#message"),
- clearBtn = $("#reset"),
- validator = null,
-
- myErrorTemplate
- = '<span class="k-widget k-tooltip k-tooltip-validation custom_validationSection">' +
- '<span class="k-icon k-i-error"></span > Hello #=message#</span > ';
-
- $(function () {
-
- if (form) {
-
- validator =form.kendoValidator({
- validateOnBlure: true,
- errorTemplate: myErrorTemplate
- }).data("kendoValidator");
- }
-
- });
-
- $(form).submit(validateMyForm);
-
- $(clearBtn).click(hideFormErrorMessages);
-
- function validateMyForm(e) {
-
- e.preventDefault();
-
- if (validator) {
-
- var resultOfValidation = validator.validate();
-
- if (!resultOfValidation) {
- messageDiv.html("Please fill up the fields properly");
- } else {
- messageDiv.html("");
- }
- }
- }
-
- function hideFormErrorMessages() {
-
- if (validator) {
-
- validator.hideMessages();
- messageDiv.html("");
- }
- }
Output
Effect on how we have changed the error-template.
Effect on setting the on-blur event to true.
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.
- <form id="basicUsage">
- <h3>ValidatioFormCompletes</h3>
- <div>
- <label>Firstname:</label>
- <input type="text" name="firstname" id="firstname" placeholder="Put your firstname" required />
- </div>
- <div>
- <label>Lastname:</label>
- <input type="text" name="lastname" id="lastname" placeholder="Put your lastname" required />
- </div>
- <div>
- <label>Email:</label>
- <input type="email" name="email" id="email" placeholder="Put your email" required />
- </div>
- <div id="message">
-
- </div>
- <div>
- <button type="submit">Submit</button>
- <button type="reset" id="reset">Clear</button>
- </div>
- </form>
- var form = $("#basicUsage"),
- messageDiv = $("#message"),
- clearBtn = $("#reset"),
- validator = null,
- myErrorTemplate = '<span class="k-widget k-tooltip k-tooltip-validation custom_validationSection">' +
- '<span class="k-icon k-i-error"></span >Hello #=message#</span >';
-
- $(function () {
-
- if (form) {
-
- validator = form.kendoValidator({
- validateOnBlur: true,
- errorTemplate: myErrorTemplate,
- validate: function (e) {
- if (e.valid === true) {
-
- toggleControls();
- toggleErrorSummary();
-
- kendo.ui.progress(form, true);
-
- setTimeout(function () {
- kendo.ui.progress(form, false);
- toggleControls();
- kendo.alert("Your registration was succesful!");
- $(clearBtn).trigger("click");
- }, 500);
-
- }
- else {
- toggleErrorSummary(true);
- }
-
- return false;
- }
- }).data("kendoValidator");
- }
- });
-
- $(clearBtn).click(hideFormErrorMessages);
-
- $(form).submit(function () {
- return false;
- });
-
- function hideFormErrorMessages() {
-
- if (validator) {
- toggleErrorSummary();
- validator.hideMessages();
- }
- }
-
- function toggleErrorSummary(show) {
-
- if (show === true) {
- messageDiv.html("Please fill up the fields properly");
-
- } else {
- messageDiv.html("");
- }
- }
-
- function toggleControls() {
-
- if (form.find("input, button").attr("disabled")) {
- form.find("input, button").attr("disabled", false);
- } else {
- form.find("input, button").attr("disabled", true);
- }
- }
Output
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.
- <form id="basicUsage" method="post">
- <h3>DefaultRulesWithCustomMessage</h3>
- <div>
- <label>Firstname:</label>
- <input type="text" name="firstname" id="firstname" placeholder="Put your firstname" required
- data-required-msg="Your firstname is required! :-)" />
- </div>
- <div>
- <label>Lastname:</label>
- <input type="text" name="lastname" id="lastname" placeholder="Put your lastname" required
- data-required-msg="Your lastname is required! :-)"/>
- </div>
- <div>
- <label>BirthDate:</label>
- <input type="date" name="birthdate" id="birthdate" placeholder="Your birthdate" required
- data-date-msg="Your birthdate is not recognized! :-)"/>
- </div>
- <div>
- <label>Email:</label>
- <input type="email" name="email" id="email" placeholder="Put your email" required
- data-required-msg="Your email is required! :-)"
- data-email-msg="Your email is not recognized!"/>
- </div>
- <div>
- <label>Country Code:</label>
- <input type="text" name="countryCode" id="countryCode" placeholder="Your country code" pattern="[A-Za-z]{3}"
- required
- data-required-msg="Country code is required! :-)"
- data-pattern-msg="Unable to recognize your country code!"/>
- </div>
- <div>
- <label>Number of Mobile Phones to donate:</label>
- <input type="number" id="mobilephonetodonate" name="mobilephonetodonate" step="2" min="2" max="10 required"
- data-step-msg="Steps should be divisble by 2"
- data-min-msg="Minimum of 2 should be donated"
- data-max-msg="Maximum of 10 only"/>
- </div>
- <div>
- <label>Your favorite search engine?</label>
- <input type="url" name="url" id="url" placeholder="Your favorite search engine" required
- data-required-msg="Search engine is required!"
- data-url-msg="Unable to recognize the URL you have given!"/>
- </div>
- <div id="message">
-
- </div>
- <div>
- <button type="submit">Submit</button>
- </div>
- </form>
- var form = $("#basicUsage"),
- messageDiv = $("#message"),
- validator = null;
-
- $(function () {
-
- if (form) {
-
-
- validator = form.kendoValidator().data("kendoValidator");
- console.log(validator);
- }
- });
-
- $(form).submit(validateMyForm);
-
- function validateMyForm(e) {
-
- e.preventDefault();
-
- if (validator) {
-
- var resultOfValidation = validator.validate();
-
- if (!resultOfValidation) {
- messageDiv.html("Please fill up the fields properly");
- } else {
- messageDiv.html("");
- }
- }
- }
Output
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.
- <form id="basicUsage" method="post">
- <h3>CustomRulesWithCustomMessageUsingValidationAttribute</h3>
- <div>
- <label>Username:</label>
- <input type="text" name="username" id="username" placeholder="Put your firstname"
- data-message="Username is undoubtedly required!"
- data-messageUsername="Username already exists"/>
- </div>
- <div>
- <label>Email:</label>
- <input type="email" name="myEmail" id="myEmail" placeholder="Put your email"
- data-message="Email is undoubtedly required!" />
- </div>
- <div>
- <label>Country Code:</label>
- <input type="text" name="countryCode" id="countryCode" placeholder="Your country code"
- data-message="Country-code is undoubtedly required!"
- />
- </div>
- <div id="message">
-
- </div>
- <div>
- <button type="submit">Submit</button>
- </div>
- </form>
- var form = $("#basicUsage"),
- messageDiv = $("#message"),
- validator = null;
-
- $(function () {
-
- if (form) {
- validator = form.kendoValidator({
- rules: {
- customRequired: function (input) {
- return ($.trim(input.val()) !== "");
- },
- customEmail: function (input) {
-
- var emailFormat = /^\w+([\.-]?\w+)*@@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
-
- if ($.trim(input.val()) !== "" & input.is("[name='myEmail']")) {
- return input.val().match(emailFormat);
- }
-
- return true;
- },
- usernameExists: function (input) {
- if (input.is("[name='username']")) {
- var result = true;
- $.ajax({
- url: `CheckUserName?username=${input.val()}`,
- async: false,
- success: function (response) {
-
- result = response;
- }
- });
-
- return result;
- }
-
- return true;
- }
- },
- messages: {
- customRequired: function (input) {
-
- return input.data("message");
- },
- usernameExists: function (input) {
- console.log("usernameExists");
- if (input.is("[name='username']")) {
- return input.attr("data-messageUsername");
- }
- },
- customEmail: "Invalid email!"
- }
- }).data("kendoValidator");
- }
- });
-
- $(form).submit(validateMyForm);
-
- function validateMyForm(e) {
-
- e.preventDefault();
-
- if (validator) {
-
- var resultofvalidation = validator.validate();
-
- if (!resultofvalidation) {
- messageDiv.html("please fill up the fields properly");
- } else {
- messageDiv.html("");
- }
- }
- }
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!