仅在输入值时验证Rails 3模型

时间:2010-12-29 10:00:28

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

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

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

这是我的用户模型:

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

1 个答案:

答案 0 :(得分:6)

尝试此操作而不是:allow_nil =&gt;是的,:allow_blank =&gt;真

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