2016-08-20 1 views
1

전화 번호 값이 "+48 999 888 777 \ naseasd"인 마지막 테스트를 통과하는 정규식을 작성하는 데 문제가 있습니다. 여기 내 파일이 있습니다. 내가 뭘 잘못하고있어?줄 바꿈 문자로이 전화 번호를 허용하지 않으려면 Regex를 작성하는 방법은 무엇입니까?

응용 프로그램/모델/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 

사양/모델/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)>' 
+0

처음에 '\ A'를 추가하고 패턴 끝에 '\ z'를 추가하십시오. –

+0

감사! 이제 작동 중입니다. 여기에 대한 자세한 정보를 찾았습니다 : [차이는 \ A \ z와^$ 사이의 루비 정규식] (http://stackoverflow.com/questions/577653/difference-between-az-and-in-ruby-regular- 표현). 나는 더 일찍^$을 사용했다. –

답변

0

귀하의

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

은 패턴이 전체 문자열에만 일치하도록합니다.

처음에는 \A을 추가하고 패턴 끝에는 \z을 추가하십시오.

^은 Ruby의 행 시작 부분에서 일치하고 ($은 행 끝에 부합 함) RoR에서 일반적으로 예외가 발생합니다. \z 앵커는 \Z이 문자열의 마지막 개행 전에 일치하고 \z이 문자열의 맨 끝에 만 일치하기 때문에 유효성 검사를 위해 \Z보다 좋습니다.