【问题标题】:Only validate an Rails3 Model when an value entered仅在输入值时验证 Rails3 模型
【发布时间】:2010-12-29 10:00:27
【问题描述】:

我需要在我的 rails3 应用程序中验证名为 phone_number 的文件。此字段是可选的,但当用户输入电话号码时,我将检查格式。 RSpec2 测试运行良好,但是当我转到 sign_up 视图并且不触摸 phone_number 字段时,我变成了“电话号码太短(最少 6 个字符)”和“电话号码无效”错误。

我的模型有什么问题?我的目标是验证 phone_number 如果用户输入此号码,如果号码为空,我将在我的数据库中保存 nil。

这是我的用户模型:

class User < ActiveRecord::Base
  belongs_to :address  
  accepts_nested_attributes_for :address

  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable, :lockable and :timeoutable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :confirmable, :lockable, :validatable

  # Setup accessible (or protected) attributes for your model
  attr_readonly :username
  attr_accessible :email, :password, :password_confirmation, :remember_me, :phone_number, :username, :newsletter, :address_attributes

  validates :username, :presence => true, :uniqueness => true, :length => {:minimum => 4, :maximum => 16 }, :format => { :with => /\A[a-z0-9][a-z0-9._-]*\z/i }
  validates :phone_number, :length => {:minimum => 6, :maximum => 25}, :format => { :with => /\A\S[0-9\+\/\(\)\s\-]*\z/i }, :allow_nil  => true
  validates :address, :presence => true
end

我的 Rspec 方法来测试 phone_number:

it "should be valid without an phonenumber" do
    Factory.build(:user, :phone_number  => nil).should be_valid
  end

  it "should be invalid with an invalid phonenumber" do   
    invalid_phonenumbers.each do |invalid|
      Factory.build(:user, :phone_number  => invalid).should_not be_valid
    end
  end

  it "should be valid with an valid phonenumber" do
    valid_phonenumbers.each do |valid|
      Factory.build(:user, :phone_number  => valid).should be_valid
    end
  end

  def invalid_phonenumbers
    ["Hans Wurst","+49 221 Hans","Gebe ich nicht ein","        ","110",""]
  end

  def valid_phonenumbers
    ["+492203969534","0221/549534","0800-2222 800","+49-0221-2222-390","+49 (221) / 549534 - 23","+49 (0) 221 / 549534 - 23","0221269534"]          
  end

【问题讨论】:

    标签: ruby validation ruby-on-rails-3


    【解决方案1】:

    试试这个而不是 :allow_nil => true, :allow_blank => true

    validates :phone_number, :length => {:minimum => 6, :maximum => 25}, :format => { :with => /\A\S[0-9\+\/\(\)\s\-]*\z/i }, :allow_blank => true
    

    【讨论】:

    • 谢谢,这适用于视图。但在我的 rspec 中 phone_number " " 是有效的。我的数据库中不会有空刺
    • :presence => false 抛出异常。
    猜你喜欢
    • 1970-01-01
    • 2017-12-16
    • 2011-06-01
    • 2018-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-11
    • 1970-01-01
    相关资源
    最近更新 更多