简体   繁体   中英

Redactor JS - validate form using BootstrapValidator

I'm having a Rails app where I use Redactor for rich text input. The form is placed inside a Bootstrap modal. I want to validate (presence) while the user types, and show a validation error if the field is empty. I'm using BootstrapValidator for the validation part. I currently don't get any validation messages for the redactor text area.

The relevant part of the code looks like this:

= form_for idea, remote: remote, html: {role: :form, "data-model" => 'idea', multipart: true}  do |f|

  # This field  / validation works
  .form-group
    = f.label :title, "Title", :class => "required"
    = f.text_field :title, :class => "form-control"

  # This does not
  .form-group
    = f.label :description, :class => "required"
    = f.text_area :description, :class => "form-control big-text-area redactor"

And the Javascript looks like this:

:javascript

  $('#new_idea').bootstrapValidator({
    message: 'This value is not valid',

    feedbackIcons: {
      valid: 'fa fa-check-square',
      invalid: 'fa fa-warning',
      validating: 'fa fa-circle-o-notch spin'
    },

    fields: {
      "idea[title]": {
        validators: {
          notEmpty: {
            message: 'The title is required'
          }
        }
      },

      "idea[description]": {
        validators: {
          callback: {
            message: 'The idea description is required',
            callback: function(value, validator) {

              # NOTE: This part of the code never get called                 

              var code = $('[name="idea[description]"]').code();
              return (code !== '' && code !== '<p><br></p>');
            }
          }
        }
      }
    }
  })

  $('.redactor').redactor({

    keyupCallback: function (e) {
      validateEditor();
    }
  });

  function validateEditor() {
    $('#new_idea').bootstrapValidator('revalidateField', "idea[description]");
  };

Any ideas on what I can do to get the validation to work?

I ran into something similar when using Redactor so perhaps this will help. In my case, I had a change listener on the textarea to which Redactor was bound to (a similar approach to what I believe Bootstrap Validator is doing) but the problem was that Redactor was eating the change event on the original textarea. To get around this, I implemented the following when initializing the Redactor plugin.

var $mytextarea = $('selector-for-textarea');
$mytextarea.redactor({
    changeCallback: function( html ) {
        $mytextarea.trigger( 'change' );
    } 
});

Hope this helps, cheers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM