[Rails] Validation 相關用法
前言
今天在使用驗證的時候覺得綁手綁腳,還是整理一些 Validation 常見使用方式來用好了。暫時先這些,之後使用到會再補充..
驗證觸發點
只有在以下method執行時,才會觸發驗證:
- create
- create!
- save
- save!
- update
- update!
驗證輔助範例
validates :terms, acceptance: true
validates :password, confirmation: true
validates :username, exclusion: { in: %w(admin superuser) }
validates :email, format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, on: :create }
validates :age, inclusion: { in: 0..9 }
validates :first_name, length: { maximum: 30 }
validates :age, numericality: true
validates :username, presence: true
validates :username, uniqueness: true
驗證輔助解說
acceptance
通常用於Checkbox(預設是1,表勾選)
validates :terms, acceptance: true
若需要指定值也可以:
validates :terms, acceptance: { accept: 'yes' }
confirmation
通常用於重複輸入驗證(ex.重複輸入一次密碼,驗證兩欄位要一樣)
validates :password, confirmation: true
對應的template長這樣:
<%= text_field :person, :password %>
<%= text_field :person, :password_confirmation %>
exclusion
這個方法驗證屬性是否“不屬於”某個給定的集合(ex.不可以註冊admin或superuser當帳號)
validates :username, exclusion: { in: %w(admin superuser) }
可以補上message:
validates :subdomain, exclusion: { in: %w(admin superuser), message: "%{value} is reserved." }
numericality
是否為數字:
validates :min_age, :numericality => true
其他限制條件:
# greater_than 大於
validates :min_age, :numericality => { :greater_than => 0 }
# greater_than_or_equal_to 大於等於
validates :min_age, :numericality => { :greater_than => 0 }
# less_than 小於
validates :max_age, :numericality => { :less_than => 100 }
# less_than_or_equal_to 小於等於
validates :max_age, :numericality => { :less_than_or_equal_to => 100 }
# odd 奇數
validates :max_age, :numericality => { :odd => true }
# even 偶數
validates :max_age, :numericality => { :even => true }
# other_than 不等於
validates :max_age, :numericality => { :other_than => 100 }
留言