使用 Summernote 编辑器进行 jQuery 验证错误:无法读取未定义的属性“替换”

问题描述 投票:0回答:12

我正在使用 MVC5 通过 Summernote 编辑器构建表单。

剃须刀代码:

<div class="form-group">
      @Html.LabelFor(model => model.Content, htmlAttributes: new { @class = "control-label" })
      @Html.EditorFor(model => model.Content, new { htmlAttributes = new { @class = "form-control post-content"} })
      @Html.ValidationMessageFor(model => model.Content, "", new { @class = "text-danger" })
</div>

JS:

$('#blog-form .post-content').summernote({
  height: 400,                
  minHeight: 300,            
  codemirror: {
    theme: 'default'
  }
});

通过上述设置,编辑器控件呈现良好。但是,一旦我离开编辑器,即 onBlur,我就会在控制台中收到以下错误:

Uncaught TypeError: Cannot read property 'replace' of undefined
    at $.validator.escapeCssMeta (jquery.validate.js:1014)
    at $.validator.errorsFor (jquery.validate.js:995)
    at $.validator.prepareElement (jquery.validate.js:679)
    at $.validator.element (jquery.validate.js:466)
    at $.validator.onfocusout (jquery.validate.js:289)
    at HTMLDivElement.delegate (jquery.validate.js:411)
    at HTMLFormElement.dispatch (jquery-2.2.3.js:4737)
    at HTMLFormElement.elemData.handle (jquery-2.2.3.js:4549)
    at Object.trigger (jquery-2.2.3.js:7819)
    at Object.simulate (jquery-2.2.3.js:7890)

这是 DOM 的渲染部分:

    <div class="form-group">
        <label class="control-label" for="Content">Content</label>
        <textarea class="form-control post-content text-box multi-line" id="Content" name="Content" style="display: none;"></textarea>

        <div class="note-editor note-frame panel panel-default">    
            ...summernote generated...
        </div>

        <span class="field-validation-valid text-danger" data-valmsg-for="Content" data-valmsg-replace="true"></span>
    </div>

jQuery 版本:2.2.3

jQuery 验证版本:1.16.0

Microsoft.jQuery.Unobtrusive.Validation 版本:3.2.3

我做了一些研究,已经知道这与 Summernote 插件无关。我尝试在准备好的文档内部和外部运行以下代码,但它不起作用:

$.validator.setDefaults({
            ignore: ":hidden:not(.post-content)"
});

有什么想法吗?

javascript jquery razor asp.net-mvc-5 jquery-validate
12个回答
31
投票

我使用此脚本告诉验证器忽略 Summernote 元素。可以对其进行调整以忽略其他 HTML 编辑器生成的元素。

$('form').each(function () {
    if ($(this).data('validator'))
        $(this).data('validator').settings.ignore = ".note-editor *";
});

13
投票

没有硬编码 Id 的最简洁方法来自 JQuery.Validate github 讨论:

jQuery.validator.setDefaults({
  // This will ignore all hidden elements alongside `contenteditable` elements
  // that have no `name` attribute
  ignore: ":hidden, [contenteditable='true']:not([name])"
});

来源:https://github.com/jquery-validation/jquery-validation/issues/1875


11
投票

如果您在使用 jQuery 验证器验证表单时遇到 quill(富文本编辑器)的问题,只需执行以下操作:

$('#id-of-form-to-validate').validate({
  ignore: ".ql-container *"
  // continue validation
});

其中“#id-of-form-to-validate”可以只是一个 id、class 或 form 元素。


5
投票

您可以通过稍微调整代码来解决上述错误。

    var v = $('#myForm').validate({ 
        // exclude it from validation
        ignore: ":hidden:not(#summernote),.note-editable.panel-body"
    });

   var myElement = $('#summernote');

   myElement.summernote({
      // See: http://summernote.org/deep-dive/
      callbacks: {
         onChange: function(contents, $editable) {
          // Note that at this point, the value of the `textarea` is not the same as the one
         // you entered into the summernote editor, so you have to set it yourself to make
         // the validation consistent and in sync with the value.
         myElement.val(myElement.summernote('isEmpty') ? "" : contents);

         // You should re-validate your element after change, because the plugin will have
         // no way to know that the value of your `textarea` has been changed if the change
        // was done programmatically.
       v.element(myElement);
    }
  }
});

来源(官方):https://github.com/jquery-validation/jquery-validation/issues/1875#issuecomment-272667183


2
投票

我尝试了上述答案,但对我的情况不起作用。 这个对我有用:

jQuery.validator.setDefaults({ ignore: ":hidden:not(#summernote),.note-editable.panel-body"});

2
投票

替换validation.js中的代码

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

2
投票

此代码对我有用

$("#commentForm").validate({
    ignore: ".note-editor *"
  });

0
投票

我在测试 jQuery TE 时发现了这个线程,并出现了相同的验证器错误,可以使用类似的解决方案修复。

$('#id-of-form-to-validate').validate({
    ignore: ".jqte *"
    // continue with validation
});

0
投票

此代码对我有用:

validator = $("#form").validate({
  ignore: ":not(#summernote),.note-editable.panel-body",
  rules: {
    nombre: {
      required: true,
      minlength: 8,
      maxlength: 40
    }
  }
});

0
投票

此代码段删除错误并继续验证:

$.validator.setDefaults({
    …………
    忽略: ":hidden:not(textarea), [contenteditable='true']:not([name])",
    …………
});

0
投票

Tags 插件也有这些未命名的动态字段,因此您还可以添加全局验证参数:

ignore: ".tagify [contenteditable], .my-class [contenteditable]"

jQuery:3.5.1

jQuery 验证插件 v1.19.3


0
投票

.note-editor * esto agregamos para omitir la validacion para no generic error

$("#form-persona").validate({
    ignore: '.select2-input, .select2-focusser, .note-editor *',
    rules: {
      nombres_y_apellidos: { minlength: 50 },      
    },
    messages: {
      nombres_y_apellidos: {minlength: "Minimo 50 Caracteres"},
    },

    errorElement: "span",

    errorPlacement: function (error, element) {
      error.addClass("invalid-feedback");
      element.closest(".form-group").append(error);
    },

    highlight: function (element, errorClass, validClass) {
      $(element).addClass("is-invalid").removeClass("is-valid");
    },

    unhighlight: function (element, errorClass, validClass) {
      $(element).removeClass("is-invalid").addClass("is-valid");
    },

    submitHandler: function (e) {
      guardar_y_editar_persona(e);
    },

  });
© www.soinside.com 2019 - 2024. All rights reserved.