rails常用的验证
#旧验证方式
rails验证机制常用于空字串的验证,字段唯一性验证,字段长度的验证,密码一致性验证,以及正则表达式匹配验证等五种。如:
validates_presence_of :login, :message => "用户名不能为空!"
validates_length_of :login, :maximum => 20, :message => "用户名长度不得长于20位字母或数字!"
validates_uniqueness_of :login,:case_sensitive => false, :message => "该用户名已存在!"
validates_presence_of :password, :message =>"密码不能为空!"
validates_length_of :password, :minimum => 6, :message=>"密码长度不得短于6位字母或数字! "
validates_presence_of :password_confirmation, :message =>"请再输入一次密码!", :allow_blank => true
validates_confirmation_of :password, :message => "两次密码不一致!"
validates_format_of :email, :message => "邮箱格式不正确!", :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i
--------------------------------------------------------------------
class Player < ActiveRecord::Base
validates_numericality_of :points #必须是数值
validates_numericality_of :games_played, :only_integer => true # 必須是整數
validates_numericality_of :age, :greater_than => 18
end
除了 greater_than,還有 greater_than_or_equal_to, equal_to, less_than, less_than_or_equal_to 等參數可以使用。
class BillingAccountType < Base
acts_as_type :payment_types, [:银行卡, :支付宝]
validates_presence_of :shop_id, :payment_types //必填
validates_numericality_of :quantity, greater_than_or_equal_to: 0 //数值大于等于0
validates_presence_of :alipay_number,:alipay_holder ,if: :require_alipay?
validates_presence_of :depositary_bank,:bank_card_number,:bank_card_holder, if: :require_bank?
def require_alipay?
self.payment_types=="支付宝"
end
def require_bank?
self.payment_types=="银行卡"
end
end
-----------------------
message
設定驗證錯誤時的訊息,若沒有提供則會用 Rails 內建的訊息。
class Account < ActiveRecord::Base
validates_uniqueness_of :email, :message => "你的 Email 重複了"
end
validates_presence_of :start_at, :end_at
validate :check_date
private
def check_date
self.errors[:start_at] << "开始日期必须小于等于结束日期" if start_at.present? && end_at.present? && start_at > end_at
end
class User < ActiveRecord::Base
EMAIL = /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i
validates :name, presence: true, length: {maximum: 10}
validates :email, presence: true,length: {maximum: 10}, format: { with: EMAIL } ,uniqueness: {case_sensitive: false}
end
添加索引
class AddIndexToUsersEmail < ActiveRecord::Migration
def change
add_index :users, :email, unique: true //邮箱唯一性约束
end
end
回调
以下是當一個物件儲存時的流程,其中1~7就是回呼可以觸發的時機:
(-) save
(-) valid
(1) before_validation
(-) validate
(2) after_validation
(3) before_save
(4) before_create
(-) create
(5) after_create
(6) after_save
(7) after_commit