簡體   English   中英

ruby on rails-測試特定的電話號碼

[英]ruby on rails - test for specific phone number of digits

這是我的代碼

test 'phonenumber should be 11 digits' do
  @user.phonenumber = 11
  assert_not @user.valid?
end

這是我的模型驗證,我正在使用gem phonelibs

class User < ApplicationRecord
  before_save { email.downcase! }
  validates :name, presence: true, length: { maximum: 50 }
  validates :phonenumber, phone: { possible: true, allow_blank: true }

  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
  validates :email, presence: true, length: { maximum: 256 },
                    format: { with: VALID_EMAIL_REGEX },
                    uniqueness: { case_sensitive: false }
  has_secure_password
  validates :password, presence: true, length: { minimum: 6 }
end

這已經添加了驗證,因為它使用Google libphonenumber,對於尼日利亞,它是11

Phonelib.default_country = 'NG'

但這不是測試電話號碼的確切數字

您已經在其他地方使用了一些長度驗證-我建議您在phonenumber字段中使用相同的長度驗證,否則該驗證將因為太短而無法通過驗證。

IE瀏覽器

validates_length_of :phonenumber, is: 11

要么

validates :phonenumber, length: { is: 11 }

或使用正則表達式:

validates_format_of :phonenumber, with: /[0-9]{11}/

可以在此處找到文檔-希望對您有所幫助!

PhoneLib根據國家/地區及其電話號碼格式提供了許多額外的功能- 最好的方法是正確地對此進行挖掘,並基於固定或基於用戶的位置使用其驗證。

但是,上述應確保phonenumber的長度為11。


更新:

gem有多種檢查電話號碼有效性的方法,例如:

Phonelib.valid? '123456789'

Phonelib.valid_for_country? '123456789', 'XX'

您還需要在config/initializers/phonelib.rbconfig/initializers/phonelib.rb如果您可以將該代碼添加到您的問題中,將很有用。

但是,要利用此功能,您的測試可能類似於:

test 'phonenumber should be 11 digits' do
  @user.phonenumber = 11
  assert_not Phonelib.valid?(@user.phonenumber)
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM