I tried to express the phone number (landline / mobile phone) with a regular expression in Rails and write validation and test

Introduction

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)

Phone number prerequisites

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

Expressed as a regular expression (copy and paste is OK !!)

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> 正規表現_Rubular.png

Explanation of regular expressions

\ 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】 正規表現_固定.png

【mobile phone】 正規表現_携帯.png

Validation and testing with Rspec

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

Recommended Posts

I tried to express the phone number (landline / mobile phone) with a regular expression in Rails and write validation and test
I tried to express the result of before and after of Date class with a number line
I tried to organize the session in Rails
[Rails] I tried to create a mini app with FullCalendar
I want to call a method and count the number
A story I was addicted to in Rails validation settings
[Rails 6.0, Docker] I tried to summarize the Docker environment construction and commands necessary to create a portfolio
I tried to illuminate the Christmas tree in a life game
I tried to sort the data in descending order, ascending order / Rails
I tried to write code like a type declaration in Ruby
Build a bulletin board API with authentication authorization in Rails 6 # 11 User model test and validation added
I tried to implement the image preview function with Rails / jQuery
Replace with a value according to the match with a Java regular expression
I want to extract between character strings with a regular expression
I tried to make a group function (bulletin board) with Rails
I tried to build a Firebase application development environment with Docker in 2020
I tried to solve the tribonacci sequence problem in Ruby, with recursion.
I want to ForEach an array with a Lambda expression in Java
<java> Split the address before and after the street address with a regular expression
I tried to measure and compare the speed of GraalVM with JMH
I want to write a unit test!
[Rails / JavaScript / Ajax] I tried to create a like function in two ways.
I tried to convert JavaBean and XML with Jackson formatter XML in this era
I tried to make a web application that searches tweets with vue-word cloud and examines the tendency of what is written in the associated profile
I rewrote the Rails tutorial test with RSpec
[Rails] I tried to raise the Rails version from 5.0 to 5.2
I tried to break a block with java (1)
I tried to create a shopping site administrator function / screen with Java and Spring
Write a test by implementing the story of Mr. Nabeats in the world with ruby
[Rails] I want to display the link destination of link_to in a separate tab
[Java] Cut out a part of the character string with Matcher and regular expression
I tried to organize the cases used in programming
I tried to read and output CSV with Outsystems
To implement, write the test and then code the process
I tried to decorate the simple calendar a little
[Rails] I tried playing with the comment send button
I started MySQL 5.7 with docker-compose and tried to connect
I want to use a little icon in Rails
I tried to create a Clova skill in Java
I tried to make a login function in Java
[How to insert a video in haml with Rails]
[JUnit 5] Write a validation test with Spring Boot! [Parameterization test]
How to write a date comparison search in Rails
I want to define a function in Rails Console
I tried to implement the Euclidean algorithm in Java
[Ruby/Rails] How to generate a password in a regular expression
Building a bulletin board API with authentication authorization with Rails 6 Validation and test implementation of # 4 post
After posting an article with Rails Simple Calendar, I want to reflect it in the calendar.
Click the [rails] button to create a random alphanumeric password and enter it in the password field
^, $ in Rails regular expression
I tried to create a java8 development environment with Chocolatey
I tried to introduce Bootstrap 4 to the Rails 6 app [for beginners]
I tried to modernize a Java EE application with OpenShift.
I tried to increase the processing speed with spiritual engineering
I tried to summarize the basics of kotlin and java
I want to make a list with kotlin and java!
I want to make a function with kotlin and java!
I tried JAX-RS and made a note of the procedure
I tried using Hotwire to make Rails 6.1 scaffold a SPA
I want to create a form to select the [Rails] category
[Rails] I tried to implement batch processing with Rake task