Jquery validation not working with ckeditor

天大地大妈咪最大 提交于 2019-11-26 14:48:28

问题


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,
                     minlenght:10
                    }
                 }
            });
        });
      </script>

FYI : jquery validation working for other form fields expect the ckeditor textarea filed

Any suggestions.. to get rid of this problem..


回答1:


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...




回答2:


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/




回答3:


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();
        });
    }



回答4:


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.




回答5:


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/




回答6:


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.




回答7:


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!!!




回答8:


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.



来源:https://stackoverflow.com/questions/22248918/jquery-validation-not-working-with-ckeditor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!