【问题标题】:How do I validate password on the base of a condition?如何根据条件验证密码?
【发布时间】:2020-02-10 07:56:04
【问题描述】:

我希望密码仅用于网络注册而不是移动应用注册。 我的验证码如下:

  class User < ApplicationRecord
    validate :password_for_web
    validate :password_confirmation_for_web

  def password_for_web
    if  !app_user && password.blank? 
    errors.add(:password, "can't be blank.")
  end
end

 def password_confirmation_for_web
   if  !app_user && password != self.password_confirmation=
       errors.add(:password_confirmation, "doesn't match.")
   end
 end

 end

验证工作正常,但在注册移动应用时仍需要密码。关于这个问题的帮助将是可观的。

【问题讨论】:

  • 注册过程web/app有什么区别?
  • 对于手机 api 注册,我们只需要电话号码而不是密码,但对于网络注册,密码是强制性的。我需要一种可以区分 Web 注册和 api 注册的自定义验证功能。我设置了一个标志是 app_user:boolean。如果为true则表示注册来自api。

标签: ruby-on-rails validation model


【解决方案1】:

您可以使用if:unless: 选项来切换验证:

class User < ApplicationRecord
  validates :password, presence: true, confirmation: true, unless: :app_user?
  # or 
  validates :password, presence: true, confirmation: true, if: :web_user?

  # TODO implement app_user?
end

您可以传递符号(方法名称)或 lambda。

【讨论】:

    【解决方案2】:

    如果您使用的是响应式设计的简单 Rails 应用。

    您需要首先检查设备是移动设备还是其他设备。您可以通过多种方式做到这一点。

    自定义方式:

    在 application_helper.rb 中:

    def mobile_device
      agent = request.user_agent
      return "tablet" if agent =~ /(tablet|ipad)|(android(?!.*mobile))/i
      return "mobile" if agent =~ /Mobile/
      return "desktop"
    end
    

    然后你可以在你的视图中使用它:

    <% if mobile_device == "mobile" %>
        //add extra parameter to check in model
        <% form_tag :mobile_device, true %>
    <% end %>
    

    在你的模型中:

    class User < ApplicationRecord
      validate :password_for_web, if: :mobile_device?
      validate :password_confirmation_for_web, if: :mobile_device?
    
      def password_for_web
        if  !app_user && password.blank? 
            errors.add(:password, "can't be blank.")
        end
      end
    
      def password_confirmation_for_web
        if  !app_user && password != self.password_confirmation=
        errors.add(:password_confirmation, "doesn't match.")
        end
      end
    
      def mobile_device?
        mobile_device.present?
      end
    end
    

    您还可以使用 gem 来检查移动设备,例如:

    https://github.com/fnando/browser

    https://github.com/shenoudab/active_device

    如果您有单独的移动应用。

    在您的移动应用程序注册表单中添加额外的参数,就像我在视图中使用的名称为mobile_device。使用更新的模型代码,您就完成了。

    【讨论】:

    • 感谢@Dipak Gupta,使用术语 app_user 我的意思是 REST Api 请求不是来自移动设备的请求,而是来自移动应用程序的请求。
    • 如果来自移动应用程序的请求,您可以在 api 中使用额外的参数。在此基础上,您可以运行条件回调
    • 是的,我用过app_user,请看我的自定义验证方法。它没有收到任何从移动应用程序发送的布尔值作为 app_user=true,实际上问题是这个
    猜你喜欢
    • 2023-03-22
    • 2012-07-03
    • 2012-11-05
    • 1970-01-01
    • 2015-04-29
    • 1970-01-01
    • 2012-11-16
    • 2012-02-25
    • 1970-01-01
    相关资源
    最近更新 更多