Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Using the jQuery Validate Plugin with CKEditor

DZone's Guide to

Using the jQuery Validate Plugin with CKEditor

· Web Dev Zone
Free Resource

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

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):<br>
  <input type="text" name="title" id="title" placeholder="Title"><br>
  
  <!-- this textarea will be replaced by a CKEditor instance -->
  Content (required):<br>
  <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.instances[textarea.id].updateElement(); // update textarea
          var editorcontent = textarea.value.replace(/<[^>]*>/gi, ''); // strip tags
          return editorcontent.length === 0;
        }
      }
    }
  });
});

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

Topics:

Published at DZone with permission of John Whish, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}