Validate CKEditor using jQuery validate


In this article we learn about how to validate CKEditor control using jquery validate

Prerequisite. Below JavaScript library are used to validate CKEditor control.
  1. Jquery-1.11.1.js
  2. Jquery.Vaidate.js


When we configure CKEditor control in our html page it render in Iframe so jquery validate library fails to check weather this control is empty or not and we face issue while validating this control. Let’s see example:
    <textarea id="txtDemo1" name="txtDemo1"></textarea>
        <textarea id="txtDemo2" name="txtDemo2"></textarea>
    <input type="submit" value="submit">

Let’s assume we have configured CKEditor for both text area control and both fields are required in system. For validation we have implemented following validation for both control as shown below:


ignore: [],
rules: {
txtDemo1: {
ckrequired: true //Custom required field 
, txtDemo2: {
 required: true  //Default required field fails

Extention method for check CKEditor Control


jQuery.validator.addMethod("ckrequired", function (value, element) {
var idname = $(element).attr('id');
var editor = CKEDITOR.instances[idname];
var ckValue = GetTextFromHtml(editor.getData())
    .replace(/<[^>]*>/gi, '').trim();
    if (ckValue.length === 0) {
//if empty or trimmed value then remove extra spacing to current control
      } else {
       //If not empty then leave the value as it is
        return $(element).val().length > 0;
 }, "This field is required");

function GetTextFromHtml(html) {
            var dv = document.createElement("DIV");
            dv.innerHTML = html;
            return dv.textContent || dv.innerText || "";

From above code we have used both default required validation and ckrequired custom required method by extending jquery validate library. Along with custom method we have use one JavaScript utility function to extract text from html value after that we have trimmed value to validate trim value with extra space.

Hope this article is useful for validate CKEditor control as well as create custom validation method using jquery validate.


In this article we learn about validating CKEditor using custom jquery validation method.


Popular posts from this blog

Dynamic Query in LINQ using Predicate Builder

Common Asp.Net Tips and Tricks

Payumoney Integration With Asp.Net