2012-01-19 7 views
3

一般的な無料のEメールアドレスを使用しないようにするRails 3検証を作成しようとしています。Railsは正規表現ではないことを確認します

私の考えでは、このようなもの....

validates_format_of :email, :with => /^((?!gmail).*)$|^((?!yahoo).*)$|^((?!hotmail).*)$/ 

または

validates_exclusion_of :email, :in => %w(gmail. GMAIL. hotmail. HOTMAIL. live. LIVE. aol. AOL.), :message => "You must use your corporate email address." 

ませんでした。しかし、どちらも正しく動作します。何か案は?

答えて

6

基本的には、何にもマッチする正規表現を書いています。それを分解しましょう。

/ 
    ^(   # [ beginning of string 
    (?!gmail) # followed by anything other than "gmail" 
    .   # followed by any one character 
)$   # followed by the end the of string 
    |    # ] OR [ 
    ^(   # beginning of the string 
    (?!yahoo) # followed by anything other than "yahoo" 
    .   # followed by any one character 
)$   # followed by the end of the string 
    |    # ] OR [ 
    ^(   # beginning of the string 
    (?!hotmail) # followed by anything other than "hotmail" 
    .*   # followed by any or no characters 
)$   # followed by the end the of string 
/    # ] 

あなたがそれについて考えるとき、あなたは一致しません文字列だけが、「Gmailの、」「ヤフー、」「のhotmail」で始まるものであることを実感します - すべてのそれと同時に、不可能です。

何が本当に欲しいのはこのようなものです:

/ 
    [email protected]      # one or more characters followed by @ 
    (?!      # followed by anything other than... 
    (gmail|yahoo|hotmail) # [ one of these strings 
    \.      # followed by a literal dot 
)      # ] 
    .+      # followed by one or more characters 
    $      # and the end of the string 
/i       # case insensitive 

はそれを一緒に入れて、あなたが持っている:

expr = /[email protected](?!(gmail|yahoo|hotmail)\.).+$/i 

test_cases = %w[ [email protected] 
       [email protected] 
       [email protected] 
       [email protected] 
       quux 
       ] 

test_cases.map {|addr| expr =~ addr } 
# => [nil, nil, nil, 0, nil] 
# (nil means no match, 0 means there was a match starting at character 0) 
+0

私はあなたが私の正規表現で説明した問題を参照してください。しかし、私はvalidates_format_ofを試しました:電子メール、:with => /[email protected](?!(gmail|yahoo|hotmail)\.).+$/iしかし、これまでのところはうまくいきません。 –

+0

私はあなたの正規表現をテストし、それは動作するように見えます。私は今私のレールの検証の構文に問題があると思っている。 –

+0

特定のインスタンスで私の検証が実行されませんでした(子モデルがある場合)。それはちょうど悪い偶然のことでした。あなたのコードは完璧でした。 –

関連する問題