【问题标题】:Validate the presence of a value in another field using client side validations使用客户端验证验证另一个字段中是否存在值
【发布时间】:2015-09-23 01:35:34
【问题描述】:

我正在使用一个非常有用的 gem ClientSideValidations,它适用于除条件验证之外的所有内容,其中条件是另一个字段中存在值。

我有一个复选框字段 (:has_dog),如果选中该复选框,则会生成要验证的文本字段 (:dog_name)。现在,这一切都很好,并且符合服务器端验证的预期,但是在执行客户端时它不会验证。

条件验证在客户端为其他字段工作,例如我硬编码为 true 或在服务器端执行其他操作,但如果结果需要来自相同表单的字段,则不是。

class PetCare < ActiveRecord::Base
    validates :dog_name, presence: true, if: :has_dog?
end

表格

<%= form_for @pet_care, validate: true do |f| %>

   <%= f.label :has_dog %> 
   <%= f.check_box :has_dog %>

   <br />       

   <%= f.label :dog_name %>    
   <%= f.text_field :dog_name, validate: true  %>

<% end %>

因此,即使“has_dog”为真,客户端“dog_name”也不会得到验证。 (尽管它在服务器端工作)。我已经尝试了名称、表单类型等的所有组合。它只是看不到“has_dog”值。我即将为此编写一个自定义验证器,但对于一件非常简单的事情来说,这似乎太过分了。有没有其他人遇到过这种情况,有什么解决办法吗?

【问题讨论】:

    标签: javascript ruby-on-rails forms validation client-side-validation


    【解决方案1】:

    我希望这会有所帮助。 当我更新用户模型时,我不会以这种方式发送密码。

    #app/models/user.rb
    
    class User < ActiveRecord::Base
      attr_accessor :updating_password
      def should_validate_password?
        updating_password || new_record?
      end
    end
    

    现在在我的控制器上

    #app/controllers/users/users_controller.rb
    class Users::UsersController < UserController
      before_filter :check_password_submitted, :only => :update
      private
      def check_password_submitted
        if params[:user][:password].blank?
          params[:user].delete("password")
          params[:user].delete("password_confirmation")
          user.updating_password = false
        else
          user.updating_password = true
        end
      end
    end
    

    我知道这不会发生在前端,但它可能会提示您该做什么。

    快乐编码

    【讨论】:

    • 非常感谢您的回复,我认为我的错误是我使用的示例是密码。我将更新我的帖子以反映它不是关于密码,而是基于验证的条件验证在客户端工作的机制,因为我在服务器端拥有它。关键是,根据一个字段的值(本例为真或假),是否应验证第二个字段。
    猜你喜欢
    • 2020-10-23
    • 1970-01-01
    • 2017-04-07
    • 2015-03-01
    • 2016-01-11
    • 2021-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多