CKEditor無(wú)法驗(yàn)證的解決方案(js驗(yàn)證+jQuery Validate驗(yàn)證)

字號(hào):


    這篇文章主要為大家詳細(xì)介紹了CKEditor無(wú)法驗(yàn)證的解決方案和jQuery Validate驗(yàn)證框架,感興趣的小伙伴們可以參考一下
    最近項(xiàng)目的前端使用了jQuery,表單的前端驗(yàn)證用的是jQuery Validate,用起來(lái)很簡(jiǎn)單方便,一直都很滿(mǎn)意的。
    前段時(shí)間,根據(jù)需求為表單中的 textarea 類(lèi)型的元素加上了html富文本編輯器,用的是CKEditor,功能強(qiáng)大,定制方便,也很滿(mǎn)意。
    不過(guò)用CKEditor增強(qiáng)過(guò)的 textarea 元素,這個(gè)字段要求是非空的,在jQuery Validate總是驗(yàn)證不通過(guò),原因就是在 CKEditor 編輯器填寫(xiě)了內(nèi)容之后,編輯器并不是立即把內(nèi)容更新到原來(lái)的 textarea 元素中的,我沒(méi)仔細(xì)看源代碼,試過(guò)一種情況就是每一次提交不通過(guò),第二次提交就可以通過(guò)的,貌似編輯器是在 submit 事件之前把編輯器的內(nèi)容更新到 textarea 中的(這個(gè)是猜測(cè),不知道對(duì)不對(duì),我對(duì)jQuery 和 CKEditor 都不太熟悉,算是拿來(lái)就用,有問(wèn)題就放狗的那種)。
    于是在網(wǎng)上找到了解決問(wèn)題的代碼,代碼不是我寫(xiě)的,我只是記錄一下我遇到的問(wèn)題,代碼非原創(chuàng)。原理就是當(dāng)編輯器更新了內(nèi)容之后,立即把內(nèi)容更新到 textarea 元素。 
    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);  
        } 
    目前一切使用正常,算是解決了一個(gè)讓我頭痛的問(wèn)題。
    另一種解決思路:
    CKEditor 編輯器是增強(qiáng)過(guò)的 textarea 元素,在填寫(xiě)了內(nèi)容之后,編輯器并不立即把內(nèi)容更新到原來(lái)的 textarea 元素中的,而是等到 submit 事件之前把編輯器的內(nèi)容更新到 textarea 中.
    因此,普通的js驗(yàn)證或是jquery validate驗(yàn)證都獲取不到編輯器的值.)
    1.js驗(yàn)證
    獲取CKEditor 編輯器的值其實(shí)很容易,其值就是CKEDITOR.instances.mckeditor.getData(),實(shí)例代碼如下:
    <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("請(qǐng)輸入發(fā)表話(huà)題的標(biāo)題."); 
                        f.tbTopicHeading.focus(); 
                        return false; 
                      } 
                      if(topicHeading.length>50); 
                      { 
                       alert("話(huà)題的主題長(zhǎng)度必須在50字符以?xún)?nèi)."); 
                       f.tbTopicHeading.focus(); 
                       return false; 
                      } 
             var topicContent=CKEDITOR.instances.mckeditor.getData(); 
               
             topicContent = topicContent.replace(/^\s+/g,""); 
             topicContent = topicContent.replace(/\s+$/g,""); 
                     if (topicContent =="") 
                      { 
                        alert("請(qǐng)?zhí)顚?xiě)話(huà)題內(nèi)容."); 
                        f.mckeditor.focus(); 
                        return false; 
                      }  
                      if(topicContent.length>4000) 
                      { 
                       alert("話(huà)題內(nèi)容的長(zhǎng)度必須在4000字符以?xún)?nèi)."); 
                       f.mckeditor.focus(); 
                       return false; 
                      }       
           }  
           </script> 
    其中,mckeditor為編輯器的textarea的id和name.
    ASP.NET中也是一樣:
    復(fù)制代碼 代碼如下:
    <asp:TextBox ID="mckeditor" runat="server" TextMode="MultiLine" Width="94%" Height="400px" CssClass="ckeditor"></asp:TextBox> 
    2.jQuery Validate驗(yàn)證
    jquery的驗(yàn)證模式不能直接使用CKEDITOR.instances.mckeditor.getData()這個(gè)值.
    它是使用如下形式來(lái)提交驗(yàn)證:
    function InitRules() { 
          opts = { 
             rules: 
             { 
                tbTopicHeading:{ 
                required:true, 
                maxlength:50   
              },           
              mckeditor:{ 
                required:true, 
                maxlength:4000 
              }  
             }, 
             messages: 
             { 
              tbTopicHeading:{ 
              required:"請(qǐng)輸入發(fā)表話(huà)題的標(biāo)題.", 
              maxlength:jQuery.format("話(huà)題的主題長(zhǎng)度必須在50字符以?xún)?nèi).")  
            }, 
              mckeditor:{ 
              required:"請(qǐng)?zhí)顚?xiě)話(huà)題內(nèi)容.", 
              maxlength:jQuery.format("話(huà)題內(nèi)容的長(zhǎng)度必須在4000字符以?xún)?nèi).")  
            } 
             }  
          } 
        } 
    其中mckeditor為控件id,不僅有取值的作用,還有提示信息定位的作用.
    因此,可以在頁(yè)面加載時(shí),加入實(shí)例化編輯器代碼,實(shí)現(xiàn)編輯器更新了內(nèi)容之后,立即把內(nèi)容更新到 textarea 元素。
    代碼如下:
    <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> 
    此段代碼放在編輯器控件之下即可.完整實(shí)例如下:
    <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為T(mén)extBox mckeditor生成的對(duì)應(yīng)客戶(hù)端看到的id 
    { 
    skin : 'kama',//設(shè)置皮膚 
    enterMode : Number(2),//設(shè)置enter鍵的輸入1.<p>2為<br/>3為<div> 
    shiftEnterMode : Number(1), // 設(shè)置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")%>', //啟用瀏覽功能,正式使用場(chǎng)合可以關(guān)閉,只允許用戶(hù)上傳 
    //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>
    以上就是解決CKEditor無(wú)法驗(yàn)證的兩種方案,相信大家和小編一樣都有所收獲