Rails form validation does not work if form is initially hidden

拥有回忆 提交于 2019-12-23 03:01:59

问题


I am having a weird issue with rails form validation. Currently the validation works fine if the form is visible when the page loads but nothing happens if the form is initially hidden and displayed upon user interaction with the page.

Model

class PushNotification < ActiveRecord::Base
  belongs_to :application, foreign_key: :appId, primary_key: :appid

  validates :message, :presence => true, :length => { maximum: 75 }
  validates :max_message_frequency, :presence => true, :numericality => {:only_integer => true, :greater_than => 0}
  validates :appId, :presence => true
end

Html Form

<div id="push-message-tab" class="tab-section">
    <%= form_for(PushNotification.new,
                     url: messaging_messaging_cohort_create_push_path(@application, @cohort),
                     remote: true, validate: true,
                     html: {
                             id: :push_notification_create_form,
                             class: 'new_push_notification_create ' + (@cohort.new_record? ? 'default-segment' : ''),
                             autocomplete: "off"
                     }) do |f| %>


            <div class="push-form-component-header">
              <%= f.label :message, 'Message' %>
              <span id="message-char-counter-wrapper"><b id="char-counter">75</b> characters left</span>
            </div>
            <div class="actions">
              <%= f.submit "Save", id:'submit-push', class: 'with-spinner', data: {waiting_text: "Saving"} %>
            </div>
    <% end %>
</div>

If push-message-tab element is visible when the page loads the rails form validation works great but it doesn't when I specify style="display: none" and toggle the visibility option on the fly. The form will be sent without performing any sort of validation.

I am using rails 3.1 with ruby 1.9.2

Thank you for your support


回答1:


You seem to be using the client_side_validations gem.

Based on their documentation (https://github.com/bcardarella/client_side_validations) and assuming you are talking about client-side validations I would recommend trying something like this in your javascript:

$('#your_form').resetClientSideValidations();

Just after you set the form as being displayed.



来源:https://stackoverflow.com/questions/16448308/rails-form-validation-does-not-work-if-form-is-initially-hidden

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!