2

I've got a form that's using unobtrusive validation and works as expected for all of my fields but once I added TinyMCE (or any other WYSIWYG editor) the textarea it uses gets hidden and is preventing the field from being included in client-side validation. Is there a way I could hook into the validation to include this hidden field, or maybe a different way to hide the textarea so it gets validated before the post back?

6 Answers 6

12

I had the same issue this week. Ended up solving it with this:

// sync tinymce content to validate before submitting form
$('form input[type=submit]').click(function () {
    tinyMCE.triggerSave();
});

...we also use the save plugin, but in order to get it to trigger validation, had to put this in the TinyMCE editor template:

function onSavePluginCallback(ed) {
    var form = $(ed.formElement);
    var isValid = form.valid();
    if (isValid) {
        form.submit();
    }
}

(function () {

    tinyMCE.init({
        ...
        save_onsavecallback: 'onSavePluginCallback',
        ...

Update

That does make sense that the textarea isn't being unobtrusively validated while it's hidden. I forgot to add another piece of javascript I had to make this work:

$.validator.setDefaults({
    ignore: ''
});

By default, jquery validate ignores fields that are not visible. The default value for the ignore parameter is ':hidden'. By setting it to an empty string, you are telling jquery validate to not ignore hidden inputs.

3
  • This helped get my code working, but the client-side validation still didn't validate the textarea untill I unhid it. See my answer for my full solution. Jun 2, 2012 at 6:04
  • You can also do $('#my-form-selector').validate({ignore: ''});
    – G Mawr
    Mar 26, 2014 at 16:08
  • Rather than changing the configuration to validate all hidden fields (i.e. ignore: ''), I just added a css class to textareas I was going to use with tinyMCE. For example, add the class hidden-by-tinymce to the textarea and then configure your validation with $.validator.setDefaults({ ignore: ':hidden:not(.hidden-by-tinymce)' }); Dec 9, 2020 at 16:29
3

What I came up with for now is to unhide the textarea and then float it off screen. Then following what @danludwig said I trigger the save event on submit.

$(function () {
    var tinymce = $('#Content');
    tinymce.tinymce({
        setup: function (e) {
            e.onInit.add(function () {
                tinymce.css({
                    position: 'absolute',
                    height: 0,
                    width: 0,
                    top: -100
                }).show();
            });
        }
    });

    $('form input[type=submit]').click(function () {
        tinyMCE.triggerSave();
    });
});

I'm also using Bootstrap so to get this fully working with jQuery Validate/Unobtrusive Validation I added in the following to the top of my page.

// makes form field highlighting work with bootstrap's css
$.validator.setDefaults({
    highlight: function (element, errorClass, validClass) {
        $(element).closest('.control-group').addClass('error');
    },
    unhighlight: function (element, errorClass, validClass) {
        $(element).closest('.control-group').removeClass('error');
    }

});
$(function () {
    // makes form field highlighting work with bootstrap's css on post backs
    $('.input-validation-error').each(function (i, element) {
        $(element).closest('.control-group').not('.error').addClass('error');
    });
});

And to get the TinyMCE editor highlighted when there's an error I added this to my stylesheet.

.control-group.error table.mceLayout,
.control-group.error table.mceLayout tr.mceFirst td,
.control-group.error table.mceLayout tr.mceLast td {
    border-color: #b94a48;
}
3
  • Right! I totally forgot, there was one more piece of code I had that I forgot to put in my answer. I have updated it.
    – danludwig
    Jun 2, 2012 at 6:13
  • That is so much nicer than my hack. Thank you! Jun 2, 2012 at 6:18
  • No problem, sorry I forgot about it earlier.
    – danludwig
    Jun 2, 2012 at 6:21
1

In my situation: tinyMCE 4, Bootstrap 2.3.1 and jQuery validate 1.9 this is what works:

$('#form1').data('validator').settings.ignore = '';

Make sure to put that line inside your document ready function. Reason for that is because I have other forms on the same page that need to continue to work with the default: do not validate ':hidden' fields. Check jQuery Validate - Enable validation for hidden fields for a full explanation.

And the css for bootstrap and the new version of tinyMCE will be something like this:

.control-group.error .mce-panel {
border-color: #b94a48;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
-moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);

}

1

I tried this solution as well as a few other similar ones and was unable to get any of them to work and this is what I came up with instead. It isn't a perfect solution but does the job I needed. I did not add any other additional code to the page.

$('form button[type=submit]').not('.cancel').click(function () {
  var form = $('#FormName');
  var isValid = form.valid();
  var istinymceValid = $('#ContentField').valid();
  if (!isValid || !istinymceValid) {
    return false;
  }
  return true;
});
1

This worked for me...

    $(function () {
        var myForm = $('#MyFormId');

        $.data(myForm[0], 'validator').settings.ignore = "null";

        tinymce.init({
            selector: '.MyTextareaClass',
            height: 200,
            setup: function (editor) {
                editor.on('keyUp', function () {
                    tinyMCE.triggerSave();

                    if (!$.isEmptyObject(myForm.validate().submitted))
                        myForm.validate().form();
                });
            },
            relative_urls: false,
            theme: "modern",
            plugins: [
                "advlist autolink lists link image charmap print preview hr anchor pagebreak",
                "searchreplace wordcount visualblocks visualchars code fullscreen",
                "insertdatetime media nonbreaking save table contextmenu directionality",
                "template paste"
            ],
            paste_as_text: true,
            toolbar1: "undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image media | print preview"
        });
    });
1
  • Thanks Kassio, I just spent 3 hours trying to get this to work and your fix did the trich! Jun 9, 2018 at 17:47
0

Things have probably changed since previous answers to this were written as it's a very old question, but then again my solution just drew on what's already been written and simplified it. Assuming your text field using TinyMCE only needs to be validated when the form is being submitted and not on each key press, this will work.

  1. Add a CSS class to the textarea that's going to be replaced with a TinyMCE editor:
<textarea id='myTextArea' class='hidden-by-tinymce' rows='10'></textarea>
  1. Modify the configuration of the jQuery validation so that your textarea is not ignored, as per the docs:
$.validator.setDefaults({
    ignore: 'hidden:not(.hidden-by-tinymce)'
});
  1. Make sure you call the triggerSave() method of the TinyMCE editor when your form is submitted:
$('#myForm').submit(function(e) {
    e.preventDefault();
    tinyMCE.triggerSave(); // this is the key to making sure the TinyMCE editor is validated
    let $form = $(this);
    let isValid = $form.valid();
    if (isValid) {
        $form.submit();
    }
});

That was all I needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.