I tried to express the phone number with a regular expression to validate the phone number.
Please refer to the following for regular expressions.
Beginners welcome! Introduction to regular expressions that can be learned by hand and eyes, part 1 "Let's search for phone numbers in various formats"
Created while verifying ruby regular expression with Ruby | Rubular #ruby #regular expression
Rubular (You can check it while verifying the regular expression)
There are various combinations (number of digits, hyphens, parentheses) in the phone number, but this time we will express it on the premise of the following
·Fixed-line phone ・ 10 digits in total ・ Head is 0 ・ 4 digits at the end ・ Hyphens and parentheses may be included (not required)
·mobile phone ・ 11 digits in total ・ The 1st and 3rd digits are 0 ・ The second digit is 5-9 ・ Hyphens and parentheses may be included (not required)
The patterns of telephone numbers that satisfy these requirements are roughly classified as follows. (0 is fixed and x can be any number) ・ Landline phone (10 digits)
0x-xxxx-xxxx 0xx-xxx-xxxx 0xxx-xx-xxxx 0xxxx-x-xxxx
・ Mobile phone (11 digits) 050-xxxx-xxxx 060-xxxx-xxxx 070-xxxx-xxxx 080-xxxx-xxxx 090-xxxx-xxxx
Fixed-line phone:\A0(\d{1}[-(]?\d{4}|\d{2}[-(]?\d{3}|\d{3}[-(]?\d{2}|\d{4}[-(]?\d{1})[-)]?\d{4}\z ** Mobile phone: \ A0 [5789] 0 [-]? \ D {4} [-]? \ D {4} \ z ** </ font>
\ A: Represents an acronym \ d {n}: n digits [-(]?: Contains "-" or "(" (may not be available) |: or \ z: Last character
To make it easier to read, I tried to divide it as follows. (\d{1}[-(]?\d{4}|\d{2}[-(]?\d{3}|\d{3}[-(]?\d{2}|\d{4}[-(]?\d{1})Is long and difficult to understand"|"Line breaks with.
【Fixed-line phone】
【mobile phone】
With this in mind, I wrote a phone number validation and test.
User.rb
class User < ApplicationRecord
VALID_PHONE_NUMBER_REGEX = /\A0(\d{1}[-(]?\d{4}|\d{2}[-(]?\d{3}|\d{3}[-(]?\d{2}|\d{4}[-(]?\d{1})[-)]?\d{4}\z|\A0[5789]0[-]?\d{4}[-]?\d{4}\z/
validates :phone_number, presence: true, format: { with: VALID_PHONE_NUMBER_REGEX }
end
user_spec.rb
RSpec.describe User, type: :model do
before do
stub_const('VALID_PHONE_NUMBER_REGEX', \A0(\d{1}[-(]?\d{4}|\d{2}[-(]?\d{3}|\d{3}[-(]?\d{2}|\d{4}[-(]?\d{1})[-)]?\d{4}\z|\A0[5789]0[-]?\d{4}[-]?\d{4}\z)
end
context 'format' do
let(:user) { FactoryBot.create(:user) } #User's FactoryBot is created in a separate file.
it 'phone_The number format is correct' do
expect(user.phone_number).to match(VALID_PHONE_NUMBER_REGEX)
end
end
end
The following has been added with reference to the comments given by @jnchito. (2020/6/22)
spec/factories/users.rb
FactoryBot.define do
factory :user do
phone_number { "0#{rand(0..9)}0#{rand(1_000_000..99_999_999)}" }
# 1,The third digit is 0,10 in total-Generate an 11-digit phone number
end
end