如何编写 Regex 以不允许此 phone 数字带有换行符?

How to write Regex to not allow this phone number with newline character?

我在编写正则表达式以通过最后一个 phone 数值等于“+48 999 888 777\naseasd”的测试时遇到问题。这是我的文件。我做错了什么?

app/models/user.rb

class User < ActiveRecord::Base

  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
  :recoverable, :rememberable, :trackable, :validatable

  validates :phone_number, format: { with: /[+]?\d{2}(\s|-)\d{3}(\s|-)\d{3}(\s|-)\d{3}/, allow_nil: true }

end

spec/models/user_spec.rb

require 'rails_helper'

describe User do

  it { is_expected.to allow_value('+48 999 888 777').for(:phone_number) }
  it { is_expected.to allow_value('48 999-888-777').for(:phone_number) }
  it { is_expected.to allow_value('48 999-888-777').for(:phone_number) }
  it { is_expected.not_to allow_value('+48 aaa bbb ccc').for(:phone_number) }
  it { is_expected.not_to allow_value('aaa +48 aaa bbb ccc').for(:phone_number) }
  it { is_expected.not_to allow_value("+48 999 888 777\naseasd").for(:phone_number) }

end

控制台中的错误是:

Failures:

1) User should not allow phone_number to be set to "+48 999 888 777\naseasd"
 Failure/Error: it { is_expected.not_to allow_value("+48 999 888 777\naseasd").for(:phone_number) }
   Expected errors  when phone_number is set to "+48 999 888 777\naseasd", got errors: ["can't be blank (attribute: \"email\", value: \"\")", "can't be blank (attribute: \"password\", value: nil)"]
 # ./spec/models/user_spec.rb:9:in `block (2 levels) in <top (required)>'

你的

it { is_expected.not_to allow_value("+48 999 888 777\naseasd").for(:phone_number) }

意味着您希望您的模式只匹配整个字符串。

在开头添加 \A,在结尾添加 \z

注意在Ruby中^匹配行首(而$匹配行尾),在RoR中通常会导致异常。出于验证目的,\z 锚点优于 \Z,因为 \Z 可以匹配字符串中最后一个换行符之前,而 \z 仅匹配字符串的末尾。