Reputation: 1613
I am using jQuery to validate forms.. but when I use CKeditor and try to validate it using jQuery, it's not working.
Here is the snippet of HTML code
<form class="form-horizontal" role="form" name="f3" id="f3" >
<div class="col-xs-8">
<textarea class="ckeditor" name="cktext" id="cktext"></textarea>
</div>
<button type="submit" class="btn btn-default btn-success">Submit</button>
</form>
Here is the form validation code
<script>
$(document).ready(function(){
$("#f3").validate(
{
debug: false,
rules: {
cktext: {
required: true,
minlength: 10
}
}
});
});
</script>
FYI : jQuery validation working for other form fields expect the ckeditor textarea field
Any suggestions.. to get rid of this problem..
Upvotes: 19
Views: 57846
Reputation: 105
It is work for me like below. I added "return
".
rules : {
subject: {
required: true
},
description: {
required: function()
{
return CKEDITOR.instances.description.updateElement();
},
}
}
Upvotes: 0
Reputation: 19
in ckeditor5 you can't just get the data automatically. you have to use their function to get the data, below is the source code which is used to validate ckeditor5 with jquery.
/// below code is only requires if you dont have ckeditor5 textbox in page and you want to intialize the textbx to particular id like id="#content"
var editorTextarea;
ClassicEditor
.create (document.querySelector ('#content'))
.then (editor => {
editorTextarea = editor;
})
.catch (error => {
console.error (error);
});
/ ** This way I invoke validations, where "content" is the name of my textarea:
<div class="form-group">
<textarea name="content" id="content"><?= $data["page"]->content;?></textarea>
</div>
** /
// if have already intialized the ckeditor5 textbox than you just have to replace **editorTextarea** to with your editor name
$ .validator.addMethod ("ck_editor", function () {
var content_length = editorTextarea.getData (). trim (). length;
return content_length> 0;
}, "Please insert content for the page.");
$ ("# form_page_edit"). validate ({
ignore it:[],
rules: {
title: {
required: true,
minlength: 6,
maxlength: 255
},
url: {
required: true,
minlength: 6,
maxlength: 255
},
content: {
ck_editor: true
}
}
});
this helps you to validate ckedior5 with jquery validation
Upvotes: 0
Reputation: 330
On initialize ckeditor:
CKEDITOR.on('instanceReady', function () {
for (var i in CKEDITOR.instances) {
CKEDITOR.instances[i].on('change', function () {
this.updateElement();
});
}
});
Also don't forget to call them on validation plugin initialize:
ignore: []
But the most important of all which may seem insignificant is that the required class
should be placed in the textarea input
Upvotes: 0
Reputation: 1268
Validate ckeditor with out jquery validation plugin...
$("form").submit( function(e) {
var messageLength = CKEDITOR.instances['editor'].getData().replace(/<[^>]*>/gi, '').length;
if( !messageLength ) {
alert( 'Please enter a message' );
e.preventDefault();
}
});
Upvotes: 1
Reputation: 272
Bydefault Ckeditor field is not validate using required rule. We have to create custom validator method for this -
jQuery.validator.addMethod('ckrequired', function (value, element, params) {
var idname = jQuery(element).attr('id');
var messageLength = jQuery.trim ( CKEDITOR.instances[idname].getData() );
return !params || messageLength.length !== 0;
}, "Image field is required");
And most importantly blank the ignore array -
<script>
$(document).ready(function(){
$("#f3").validate({
ignore : [],
rules: {
cktext:{
ckrequired:true
}
}
});
});
</script>
Now you are all set.
Upvotes: 2
Reputation: 4883
Simple snippet worked for me.
CKEDITOR.replace( 'textarea_input_name');
$( "#form_id" ).submit( function( e ) {
//in case, if didn't worked, remove below comment. This will get the textarea with current status
//CKEDITOR.instances.textarea_input_name.updateElement( );
var messageLength = CKEDITOR.instances['textarea_input_name'].getData( ).replace( /<[^>]*>/gi, '' ).length;
if( !messageLength )
{
alert( 'Please fill required field `Text`' );
//stop form to get submit
e.preventDefault( );
return false;
}
else
{
//editor is not empty, proceed to submit the form
return true;
}
} );
Hope this helps!!!
Upvotes: 0
Reputation: 229
we can validate ckeditor using jquery validation by using the following piece of code.
<input type="text" name="firstname" id="firstname"/>
<textarea name="editor1" id="editor1" rows="10" cols="80"></textarea>
$("#myForm").validate({
ignore: [],
rules:{
firstname:{
required:true
},
editor1: {
required: function(textarea) {
CKEDITOR.instances[textarea.id].updateElement();
var editorcontent = textarea.value.replace(/<[^>]*>/gi, '');
return editorcontent.length === 0;
}
}
},messages:{
firstname:{
required:"Enter first name"
}
}
});
for more information about validation click here http://www.dotnetqueries.com/Article/129/validate-ckeditor-using-jquery-form-validation.
Upvotes: 2
Reputation: 123
Existing answers are good, they provide solutions for validation only on submit button, here some code for reactive validation of the ckeditor fields, like default jquery validation do. Put this on your ckeditor/config.js:
CKEDITOR.on('instanceReady', function (e) {
var instance = e.editor;
instance.on("change", function (evt) {
onCKEditorChange(evt.editor);
});
//key event handler is a hack, cause change event doesn't handle interaction with these keys
instance.on('key', function (evt) {
var backSpaceKeyCode = 8;
var deleteKeyCode = 46;
if (evt.data.keyCode == backSpaceKeyCode || evt.data.keyCode == deleteKeyCode) {
//timeout needed cause editor data will update after this event was fired
setTimeout(function() {
onCKEditorChange(evt.editor);
}, 100);
}
});
instance.on('mode', function () {
if (this.mode == 'source') {
var editable = instance.editable();
editable.attachListener(editable, 'input', function (evt) {
onCKEditorChange(instance);
});
}
});
});
function onCKEditorChange(intance) {
intance.updateElement();
triggerElementChangeAndJqueryValidation($(intance.element.$));
}
function triggerElementChangeAndJqueryValidation(element) {
element.trigger('keyup');
}
Bonus: If you are using custom submit buttons and handlers for your form, now you don't need to explicitly call CKEDITOR.instances["yourtextarea"].updateElement();
before sending form via ajax to your server.
Also dont forget to call:
jQuery.validator.setDefaults({
ignore: []
});
My CKeditor: version:"4.5.4",revision:"d4677a3" Doc for ckeditor events: http://docs.ckeditor.com/#!/api/CKEDITOR.editor. It was hard to find right doc on this site.
Upvotes: 0
Reputation: 2024
jQuery.validator.setDefaults({
ignore: [],
// with this no hidden fields will be ignored E.g. ckEditor text-area
});
I observed the validation was working on 2nd submit. The reason is, ckEditor
hides the actual text area and puts an iframe as an editor instance, and on submit it pushes the content to the text area. Which means, the validation on the TextArea
gets fired on stale data. To fix this problem, I am updating my TextArea
on the text change of the editor instance.
for (instance in CKEDITOR.instances) {
CKEDITOR.instances[instance].on('change', function ()
{
var editorName = $(this)[0].name;
CKEDITOR.instances[editorName].updateElement();
});
}
Upvotes: 2
Reputation: 1613
Finally i found the answer to my question...
I changed the value of ignore property which by default holds :hidden value. as CKEDITOR hides the textarea jQuery validation doesn't validate the element:
ignore: []
Just i changed the validation script as follows..
$(document).ready(function(){
$("#f3").validate(
{
ignore: [],
debug: false,
rules: {
cktext:{
required: function()
{
CKEDITOR.instances.cktext.updateElement();
},
minlength:10
}
},
messages:
{
cktext:{
required:"Please enter Text",
minlength:"Please enter 10 characters"
}
}
});
});
HTML snippet is
<form class="form-horizontal" role="form" name="f3" id="f3" >
<div class="col-xs-8">
<textarea class="ckeditor" name="cktext" id="cktext"></textarea>
</div>
<button type="submit" class="btn btn-default btn-success">Submit</button>
</form>
As i found this answer in Here
Thanks to all...
Upvotes: 43
Reputation: 21226
I took the previous answer and fleshed it out with an actual CKEditor, so that you can see what needs to be done to copy the contents of the CKEditor into your textarea before submit.
The key bits are this:
CKEDITOR.on('instanceReady', function () {
$.each(CKEDITOR.instances, function (instance) {
CKEDITOR.instances[instance].document.on("keyup", CK_jQ);
CKEDITOR.instances[instance].document.on("paste", CK_jQ);
CKEDITOR.instances[instance].document.on("keypress", CK_jQ);
CKEDITOR.instances[instance].document.on("blur", CK_jQ);
CKEDITOR.instances[instance].document.on("change", CK_jQ);
});
});
function CK_jQ() {
for (instance in CKEDITOR.instances) {
CKEDITOR.instances[instance].updateElement();
}
}
Which I got from this answer to a different but similar question.
The other error you have is misspelling minlength
in your rules object.
This is what it looks like working: http://jsfiddle.net/ryleyb/QcJ57/
Upvotes: 7
Reputation: 1498
You need to put a submit button in your form:
<input type="submit"/>
The form is only validate when is submitted.
Check example on this fiddle: http://jsfiddle.net/5RrGa/800/
Upvotes: -2