CKEditor with JQuery Validation

Just a quick post (mostly for my own reference!) on using the jQuery validate plugin to check that a CKEditor instance has content. The problem occurs when CKEditor replaces the HTML textarea tag with a WYSIWYG editor and the jQuery validate plugin validates against the textarea and not the content of the WYSIWYG editor.

The solution is quite simple. Just use the updateElement() method of the CKEditor instance to populate the hidden textarea before you do the validation.

Here's some code to demonstrate:

<form id="cms-form">  Title (required):  <input type="text" name="title" id="title" placeholder="Title">  <!-- this textarea will be replaced by a CKEditor instance -->  Content (required):  <textarea name="content" id="content" placeholder="Content" class="ckeditor"></textarea></form><script>jQuery(function($){  $("#cms-form").validate({    event: 'blur',    rules: {      title: {required: true},      content: {required: true}    }  });});</script>

All you need to do is to replace the line:

  content: {required: true}

With a callback so you get something like this:

jQuery(function($){  $("#cms-form").validate({    event: 'blur',    rules: {      title: {required: true},      content: {        required: function(textarea) {          CKEDITOR.instancestextarea.id.updateElement(); // update textarea          var editorcontent = textarea.value.replace(/<^>*>/gi, ''); // strip tags          return editorcontent.length === 0;        }      }    }  });});

This page was last modified on Tuesday, 4th September 2018 at 08:50:34 by Gary Keeling. © 2019 GKWeb Design.

Categorised as: CKEditor

GK5 Footer

and whatever