CKEditor 5 和 jQuery 验证错误

CKEditor 5 and jQuery Validation error

刚开始使用 CKEditor,我对收到的这个 jQuery 验证错误感到困惑。我的项目是 C# MVC 并利用 UnobtrusiveJavascript 和 Unobtrusive Validate 插件。

我有一个通过 HtmlHelper 构建的文本区域:

 @Html.TextAreaFor(model => model.BookSummary, new { id = "bookMainInfo" })

这是我创建编辑器的方法。打开页面时替换文本区域:

 var theEditor;

// Load CKEditor in place of the information table
ClassicEditor
    .create(document.querySelector('#bookMainInfo'), {
        toolbar: ['heading', 'bold', 'italic', 'underline', 'link', 'bulletedList', 'numberedList', 'blockQuote', 'undo', 'redo'],
        heading: {
            options: [
                { model: 'paragraph', title: 'Paragraph', class: 'ck-heading_paragraph' },
                { model: 'heading4', view: 'h4', title: 'Large Heading', class: 'ck-heading_heading4' },
                { model: 'heading5', view: 'h5', title: 'Medium Heading', class: 'ck-heading_heading5' },
                { model: 'heading6', view: 'h6', title: 'Small Heading', class: 'ck-heading_heading6' }
            ]
        }
    })
    .then(editor => {
        theEditor = editor; // Save editor for usage later
    })
    .catch(error => {
        console.error(error);
    });

似乎一切正常。我可以成功输入数据并毫无问题地提交表格。但是,如果我在编辑器中输入任何文本并在编辑器外部单击,控制台中会抛出以下错误:

VM149 jquery.validate.js:1033 Uncaught TypeError: Cannot read property 'replace' of undefined
at $.validator.escapeCssMeta (VM149 jquery.validate.js:1033)
at $.validator.errorsFor (VM149 jquery.validate.js:1014)
at $.validator.prepareElement (VM149 jquery.validate.js:692)
at $.validator.element (VM149 jquery.validate.js:475)
at $.validator.onfocusout (VM149 jquery.validate.js:300)
at HTMLDivElement.delegate (VM149 jquery.validate.js:424)
at HTMLFormElement.dispatch (VM148 jquery-3.3.1.js:5183)
at HTMLFormElement.elemData.handle (VM148 jquery-3.3.1.js:4991)
at Object.trigger (VM148 jquery-3.3.1.js:8249)
at Object.simulate (VM148 jquery-3.3.1.js:8318)

错误被记录了两次,我可以通过在 it.An 空编辑器中使用文本单击进出编辑器来重复生成错误,从而不会出现错误。好像是jquery.validate.js这一段具体要炸了:

    escapeCssMeta: function( string ) {
        return string.replace( /([\!"#$%&'()*+,./:;<=>?@\[\]^`{|}~])/g, "\" );
    }

我能做些什么来抑制这个错误或阻止 jQuery 验证在这里尝试做任何事情吗?它在功能上对我没有影响,但这很烦人。

所以我找到了适合我需要的解决方案。以前,#bookMainInfo TextArea 绑定到具有 [Required] 属性的模型 属性。

发生错误是因为当 jQuery 验证调用 escapeCssMeta 时,它试图 运行 在创建的 CKEditor 编辑器上进行验证。编辑器没有 Id 或 Name,因此在控制台中抛出了 "Cannot read property 'replace' of undefined" 消息。

就我而言,我能够从该字段中删除 [Required] 属性,这不再是问题。

我的错误已通过添加 .ignore = ".ck" 得到解决

$(document).ready(function() {
 $('form').each(function() {
       if $(this).data('validator')
          $(this).data('validator').settings.ignore=".ck";
 });
});
VM149 jquery.validate.js:1033 Uncaught TypeError: Cannot read property 'replace' of undefined

结果是因为 CKEditor 创建的用于编辑的元素没有属性“name”。 当然可以尝试给 CKEditor 元素一个“名称”属性...

或者您可以专门从验证中排除此元素。它只是形式上的一个工具。应验证包含来自 CKEditor 的值的实际元素。

$('FORM').validate({
      ignore: ".cke_editable"
});

https://jqueryvalidation.org/validate/#ignore