带有CKEditor的jQuery验证插件

jQuery Validation plugin with CKEditor

本文关键字:验证 插件 jQuery CKEditor 带有      更新时间:2023-09-26

我知道以前有人问过这个问题,我已经阅读了之前的所有问题,但我仍然无法让jQuery验证器正确验证CKEditor字段。

我的表格如下:

<form id="faq-form">
    <p>
        <label>Title:</label>
        <input type="text" id="faq-title" name="faq-title" class="faq-title" />
    </p>
    <p>
        <label for="question">Question:</label>
        <textarea name="question" id="question"></textarea>
    </p>
    <p>
        <label for="answerswer">Answer:</label>
        <textarea name="answerswer" id="answerswer"></textarea>
    </p>            
    <p>
        <input id="submit-faq" name="submit-faq" type="submit" value="Submit" />
    </p>
</form>

两个文本区域都使用转换为CKEditor字段

<script>
CKEDITOR.replace('question', { toolbar : 'forum' });
CKEDITOR.replace('answer', { toolbar : 'forum' });
</script>

当我尝试验证时,只有标题字段得到验证。我不确定我做错了什么。以下是我用于验证的javascript代码(以下位于jQuery文档就绪函数中)。

$('#faq-form').submit(function() {
    // Update textareas with ckeditor content
    for (var i in CKEDITOR.instances) {
        CKEDITOR.instances[i].updateElement();
        $.trim($('#' + i).val());
    }
    // Validate the form
    if ( ! $('#faq-form').validate({
        rules: {
            'faq-title': {
                required: true,
                minlength: 5
            },
            answer: {
                required: true,
                minlength: 20
            },
            question: {
                required: true,
                minlength: 20
            }
        }
    }).form()) {
        console.log('Form errors');
        return false;
    }

一旦验证完成,我将使用$.post方法,而不是普通的表单get或post,这样我就可以在不重新加载的情况下更新我的页面。$.帖子是在验证方法之后发布的,但我认为没有必要显示。

我终于能够让它工作了。CKEditor在运行时隐藏文本区域,jQuery验证器忽略隐藏的元素。在validate函数中,这一点可以更改。所以我的新代码如下:

if ( ! $('#faq-form').validate({
    ignore: "input:hidden:not(input:hidden.required)",
    rules: {
        'faq-title': {
            required: true,
            minlength: 5
        },
        answer: {
            required: true,
            minlength: 20
        },
        question: {
            required: true,
            minlength: 20
        }
    },
    messages: {
        'faq-title': {
            required: "The title field is required"
        },
        answer: {
            required: "The answer field is required"
        },
        question: {
            required: "The question field is required."
        }
    },
    errorElement: "span",
    errorPlacement: function (error, element) {
        error.appendTo(element.prev());
    }
}).form()) {
    console.log('Form errors');
    return false;
}

我还添加了消息,并在显示错误时修改了错误的元素和位置。我想这可能会对其他偶然发现这一点的人有所帮助。

好吧,让我们减少它,我花了几个小时把CKEditor的错误消息放在正确的位置,因为每次它出现在CKEditor顶部或标签后面,看起来都不太好。

由于CKEditor隐藏文本区域,并将其span标记放在文本区域的正后方。请使用浏览器工具检查dom元素,然后您可以看到文本区域是隐藏的。

我只是调整了代码以获得CKEditor下的错误消息标签/span。

        $('#messageForm').validate(
          {
              ignore: 'input:hidden:not(input:hidden.required)',
              rules: {
                  msgTitle: {
                      minlength: 2,
                      required: true
                  },
                  msgText: {
                      minlength: 2,
                      required: true
                  }
              },
              errorElement: "span", // can be 'label'
              errorPlacement: function (error, element) {
                  if ($(element).attr('id') == 'msgText') {
                      $('#cke_msgText').after(error);
                  } else {
                      element.after(error);
                  }
              },
              highlight: function (element) {
                  $(element).closest('.form-group').removeClass('text-success').addClass('error');
              },
              success: function (element) {
                  element
                      .closest('.form-group').removeClass('error').addClass('text-success');
              }
          });

这里,"msgText"是隐藏的文本区域的id,而ckeditor的cke_msgText id,您可以通过检查dom元素来找到id,也许ckeditor会使用文本区域的id属性并将其前缀为"cke_"。

我的猜测是,至少在默认情况下,CKEditor不能很好地进行验证。在验证之前,您需要删除编辑器(CKEditor的工作方式是隐藏正在编辑的内容,然后插入一个iframe并将可编辑的内容粘贴在其中;当您删除编辑器时,它会关闭iframe,并复制内容——至少是从内存中复制)。我的猜测是,如果您检查DOM,您会发现文本区域的内容没有改变。

你可能会发现NicEdit在这种情况下更有用——请参阅以下线程:

https://stackoverflow.com/questions/3914510/wysiwyg-editor-without-iframe

您的代码:

$('#faq-form').submit(function() {
    // Update textareas with ckeditor content
    for (var i in CKEDITOR.instances) {
        CKEDITOR.instances[i].updateElement();
        $.trim($('#' + i).val());
    }
    if ( ! $('#faq-form').validate({
        rules: {
            'faq-title': {
                required: true,
                minlength: 5
            },
            answer: {
                required: true,
                minlength: 20
            },
            question: {
                required: true,
                minlength: 20
            }
        }
    }).form()) {
        console.log('Form errors');
        return false;
    }
    ....

不应在条件中使用.validate()。这就是.valid()方法的作用。.validate()仅用于在DOM上初始化一次插件,并准备好您的规则&选项。初始化后,.valid()可以在条件语句中用于触发测试并返回布尔值。

此外,您不应该在submit处理程序中包含.validate()。该插件有自己的submitHandler回调函数。

你的代码应该改成这样的东西:

$(document).ready(function() {
    $('#faq-form').validate({ // initialize the plugin
        // rules & options,
        rules: {
            'faq-title': {
                required: true,
                minlength: 5
             },
             answer: {
                required: true,
                minlength: 20
             },
             question: {
                required: true,
                minlength: 20
             }
        },
        submitHandler: function (form) {
             // Update textareas with ckeditor content
             for (var i in CKEDITOR.instances) {
                 CKEDITOR.instances[i].updateElement();
                 $.trim($('#' + i).val());
             }
        }
    })
    if ( ! $('#faq-form').valid() ) { // test the form for validity
        console.log('Form errors');
        return false;
    }
});

迄今为止我找到的最好的解决方案,简单而优雅:

    $('#form1').validate({
        ignore: [],
        rules: {
            corpo : {
                required: function()
                {
                    CKEDITOR.instances.corpo.updateElement();
                }
            }
        }
    })

字体:http://devlog.waltercruz.com/usando-ckeditor-e-jquery-validate-juntos

    <form>
        <textarea class="ckeditor" id="noticeMessage" name="message"></textarea>
    </form>
    <script type="text/javascript" src="ckeditor/ckeditor.js"></script>

    <form>
        <textarea class="ckeditor" id="noticeMessage" name="message"></textarea>
    </form>
    <script type="text/javascript" src="ckeditor/ckeditor.js"></script>
    <script type="text/javascript">
        $("form").submit( function() {
            var messageLength = CKEDITOR.instances['noticeMessage'].getData().replace(/<[^>]*>/gi, '').length;
            if( !messageLength ) {
                alert( 'Please enter a message' );
            }
        }
    </script>
see for full reference
----------------------
http://christierney.com/2012/12/14/ckeditor-4-required-field-validation/