【发布时间】: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