Home >Web Front-end >JS Tutorial >Solution to the problem that CKEditor cannot verify (js verification jQuery Validate verification)_jquery

Solution to the problem that CKEditor cannot verify (js verification jQuery Validate verification)_jquery

WBOY
WBOYOriginal
2016-05-16 09:00:311686browse

the front-end of the recent project uses jquery, and the front-end validation of the form uses jquery validate. it is very simple and convenient to use, and i have always been very satisfied.

some time ago, an html rich text editor was added to the textarea type elements in the form according to the needs. i used ckeditor, which is powerful and easy to customize. i am also very satisfied.

however, for the textarea element enhanced with ckeditor, this field is required to be non-empty, and jquery validate always fails the verification. the reason is that after the ckeditor editor fills in the content, the editor does not immediately update the content to the original one. in the textarea element, i didn’t look at the source code carefully. one situation i tried was that every submission failed, but the second submission passed. it seems that the editor updates the editor’s content into the textarea before the submit event. (this is just a guess, i don’t know if it’s correct. i’m not very familiar with jquery and ckeditor. i just use them as they come and let them go if there are any problems).

so i found the code to solve the problem on the internet. the code was not written by me. i just recorded the problems i encountered. the code is not original. the principle is that when the editor updates the content, it immediately updates the content to the textarea element.

ckeditor.instances["page_content"].on("instanceready", function() 
    { 
            //set keyup event 
            this.document.on("keyup", updatetextarea); 
             //and paste event 
            this.document.on("paste", updatetextarea); 
 
    }); 
 
    function updatetextarea() 
    { 
        ckeditor.tools.settimeout( function() 
              {  
                $("#page_content").val(ckeditor.instances.page_content.getdata()); 
                $("#page_content").trigger('keyup'); 
              }, 0);  
    } 

everything is working normally now, which solves a headache problem for me.

another solution:

ckeditor editor is an enhanced textarea element. after filling in the content, the editor does not immediately update the content to the original textarea element. instead, it waits until the submit event to update the editor content to the textarea. .
therefore, ordinary js validation or jquery validate validation cannot obtain the editor value.)

1.js verification
it is actually very easy to get the value of the ckeditor editor. the value is ckeditor.instances.mckeditor.getdata(). the example code is as follows:

<script language="javascript" type="text/javascript">   
 
  function checkform() 
       { 
         var f=document.form1; 
         var topicheading=f.tbtopicheading.value; 
         topicheading = topicheading.replace(/^\s+/g,""); 
         topicheading = topicheading.replace(/\s+$/g,""); 
                 if (topicheading =="") 
                  { 
                    alert("请输入发表话题的标题."); 
                    f.tbtopicheading.focus(); 
                    return false; 
                  } 
                  if(topicheading.length>50); 
                  { 
                   alert("话题的主题长度必须在50字符以内."); 
                   f.tbtopicheading.focus(); 
                   return false; 
                  } 
         var topiccontent=ckeditor.instances.mckeditor.getdata(); 
          
         topiccontent = topiccontent.replace(/^\s+/g,""); 
         topiccontent = topiccontent.replace(/\s+$/g,""); 
                 if (topiccontent =="") 
                  { 
                    alert("请填写话题内容."); 
                    f.mckeditor.focus(); 
                    return false; 
                  }  
 
                  if(topiccontent.length>4000) 
                  { 
                   alert("话题内容的长度必须在4000字符以内."); 
                   f.mckeditor.focus(); 
                   return false; 
                  }       
 
       }  
       </script> 

among them, mckeditor is the id and name of the editor's textarea.
the same is true in asp.net:

copy code the code is as follows:

2.jquery validate
jquery’s verification mode cannot directly use the value of ckeditor.instances.mckeditor.getdata().
it is submitted for verification using the following form:

function initrules() { 
      opts = { 
         rules: 
         { 
            tbtopicheading:{ 
            required:true, 
            maxlength:50   
          },           
          mckeditor:{ 
            required:true, 
            maxlength:4000 
          }  
         }, 
         messages: 
         { 
          tbtopicheading:{ 
          required:"请输入发表话题的标题.", 
          maxlength:jquery.format("话题的主题长度必须在50字符以内.")  
        }, 
          mckeditor:{ 
          required:"请填写话题内容.", 
          maxlength:jquery.format("话题内容的长度必须在4000字符以内.")  
        } 
         }  
      } 
    } 

among them, mckeditor is the control id, which not only has the function of obtaining value, but also has the function of positioning prompt information.
therefore, you can add instantiation editor code when the page is loaded, so that after the editor updates the content, it will immediately update the content to the textarea element.

the code is as follows:

<script type="text/javascript"> 
//<![cdata[ 
ckeditor.instances["mckeditor"].on("instanceready", function()    
    {    
            //set keyup event  
            this.document.on("keyup", updatetextarea);  
             //and paste event 
            this.document.on("paste", updatetextarea);   
    });    
 
    function updatetextarea()  
    {    
        ckeditor.tools.settimeout( function() 
              {    
                $("#mckeditor").val(ckeditor.instances.mckeditor.getdata());    
                $("#mckeditor").trigger('keyup');    
              }, 0);  
    }   
//]]> 
              </script> 

this code can be placed under the editor control. the complete example is as follows:

<asp:TextBox ID="mckeditor" runat="server" TextMode="MultiLine" Width="98%" Height="400px" CssClass="ckeditor"></asp:TextBox> 
<script type="text/javascript"> 
//<![CDATA[ 
CKEDITOR.replace( '<%=mckeditor.ClientID %>',// mckeditor.ClientID为TextBox mckeditor生成的对应客户端看到的id 
{ 
skin : 'kama',//设置皮肤 
enterMode : Number(2),//设置enter键的输入1.<p>2为<br/>3为<div> 
shiftEnterMode : Number(1), // 设置shiftenter的输入 
disableNativeSpellChecker:false,  
scayt_autoStartup:false, 
toolbar_Full : [ 
['Source','-','Save','NewPage','Preview','-'], 
['Cut','Copy','Paste','PasteText','PasteFromWord','-'], 
['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'], 
['NumberedList','BulletedList','-','Outdent','Indent'], 
['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'], 
['Link','Unlink','Anchor'], 
['Image','Table','HorizontalRule'],['Subscript','Superscript'], 
'/', 
['Bold','Italic','Underline'], 
['TextColor','BGColor'], 
['Styles','Format','Font','FontSize'] 
], 
//filebrowserBrowseUrl: '<%=ResolveUrl("~/ckfinder/ckfinder.html")%>', //启用浏览功能,正式使用场合可以关闭,只允许用户上传 
//filebrowserImageBrowseUrl:'<%=ResolveUrl("~/ckfinder/ckfinder.html?Type=Images")%>', 
//filebrowserImageUploadUrl:'<%=ResolveUrl("~/ckfinder/core/connector/aspx/connector.aspx?command=QuickUpload&type=Images")%>' 如果使用ckfinder 就不要屏蔽 
//自定义的上传 
filebrowserImageUploadUrl:'<%=ResolveUrl("~/fileupload/fileupload.aspx?command=QuickUpload&type=Images")%>' 
}); 
CKEDITOR.instances["mckeditor"].on("instanceReady", function()  
    { 
            //set keyup event 
            this.document.on("keyup", updateTextArea);  
             //and paste event 
            this.document.on("paste", updateTextArea);  
    });  
 
    function updateTextArea() 
    { 
        CKEDITOR.tools.setTimeout( function()  
              { 
                $("#mckeditor").val(CKEDITOR.instances.mckeditor.getData());  
                $("#mckeditor").trigger('keyup');  
              }, 0);  
    }   
//]]> 
              </script> 

the above are two solutions to the problem that ckeditor cannot verify. i believe that everyone will gain something like the editor. thank you for reading.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn