Introduction
In this article we learn about how to validate CKEditor control using jQuery validate.
Prerequisite
The following JavaScript library is used to validate CKEditor control.
Description
When we configure CKEditor control in our html page it renders in Iframe, so jquery validate library fails to check wthether this control is empty or not and we face issue while validating this control. Let’s see an example.
HTML
<form>
<textarea id="txtDemo1" name="txtDemo1"></textarea>
<textarea id="txtDemo2" name="txtDemo2"></textarea>
<input type="submit" value="submit">
</form>
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 in the following example.
Script
$("form").validate({
ignore: [],
rules: {
txtDemo1: {
ckrequired: true // Custom required field
},
txtDemo2: {
required: true // Default required field fails
}
}
});
// Extension method to check CKEditor Control
// jQuery.validator.addMethod("customfunctionname", validationfunction, validationmessage);
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 from current control
$(element).val(ckValue);
} else {
// If not empty, leave the value as it is
$(element).val(editor.getData());
}
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 the 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 used one JavaScript utility function to extract text from html value and 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.
Conclusion
In this article we learned about validating CKEditor using custom JQuery validation method.