10

ねえ...full_nameフィールド(名前の名前)をどのように検証しますか。

4

3 に答える 3

32

次のような名前を検討してください。

  • ジャン・レビンソン・グールドさん
  • マーティン・ルーサー・キング・ジュニア博士
  • ブレット・ダラス・ドートレーシー
  • ブルーノ

そこにある文字を検証する代わりに、文字のセットが存在しないことを確認したいだけかもしれません。

例えば:

class User < ActiveRecord::Base

  validates_format_of :full_name, :with => /\A[^0-9`!@#\$%\^&*+_=]+\z/
  # add any other characters you'd like to disallow inside the [ brackets ]
  # metacharacters [, \, ^, $, ., |, ?, *, +, (, and ) need to be escaped with a \

end

テスト

Ms. Jan Levinson-Gould         # pass
Dr. Martin Luther King, Jr.    # pass
Brett d'Arras-d'Haudracey      # pass
Brüno                          # pass
John Doe                       # pass
Mary-Jo Jane Sally Smith       # pass
Fatty Mc.Error$                # fail
FA!L                           # fail
#arold Newm@n                  # fail
N4m3 w1th Numb3r5              # fail

正規表現の説明

NODE                     EXPLANATION
--------------------------------------------------------------------------------
  \A                       the beginning of the string
--------------------------------------------------------------------------------
  [^`!@#\$%\^&*+_=\d]+     any character except: '`', '!', '@', '#',
                           '\$', '%', '\^', '&', '*', '+', '_', '=',
                           digits (0-9) (1 or more times (matching
                           the most amount possible))
--------------------------------------------------------------------------------
  \z                       the end of the string
于 2010-04-13T15:16:08.817 に答える
1

ここで実行する検証は、非常に一般的でない限り、失敗する可能性があります。たとえば、最小の長さを 3 に強制することは、入力内容の詳細に入ることなく取得できるのとほぼ同じくらい合理的です。

アポストロフィ付きの「O'Malley」、ダッシュ付きの「Smith-Johnson」、アクセント付き文字の「Andrés」、または実質的に文字がまったくない「Vo Ly」などの非常に短い名前がある場合、どのように検証しますか?正当なケースを除外せずに?簡単ではない。

于 2010-04-13T14:10:42.127 に答える