Rails验证full_name

10

嘿...你如何验证完整姓名字段(名字和姓氏)。


需要一些好的正则表达式来验证格式。 - xpepermint
1
什么值是可以接受的,什么值不可以接受?在我看来,你只需要检查是否包含特殊字符,如#@%...,数字,并且至少有一个空格。 - Draco Ater
有些人只有一个名字,所以即使寻找空格也可能会出现问题。问问自己:我为什么要验证姓名字段?你试图防止发生什么问题? - Larry K
3个回答

33

考虑以下名称:

  • Ms. Jan Levinson-Gould
  • Dr. Martin Luther King, Jr.
  • Brett d'Arras-d'Haudracey
  • Brüno

你可能只想确保某些字符不存在,而不是验证那里有哪些字符。

例如:

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

我在Rails 4.0.1上发现了这个问题。提供的正则表达式使用多行锚点(^或$),这可能存在安全风险。您是想使用\A和\z,还是忘记添加:multiline => true选项?但是通过添加:multiline => true已经解决了这个问题validates_format_of :name, :with => /^[^0-9`!@#\$%\^&*+_=]+$/, :multiline => true - barek2k2
@barek2k2,我应该在这里使用\A\z。感谢您的评论。 - maček
2
有点晚了... 但是请记住,这个正则表达式批准名称为 ------ - ExcellentAverage
考虑非英语为母语的人(如西里尔字母中的名称等)。这是一团糟。 - Serge Vinogradov

1

在这里进行的任何验证,除非极为普遍,否则很可能会崩溃。例如,强制最小长度为3可能是您可以做到而不涉及输入内容的特定性的最合理选择。

当您有像带撇号的“O'Malley”,带破折号的“Smith-Johnson”,带重音字符的“Andrés”或几乎没有字符的“Vo Ly”等极短名称时,如何进行验证而不排除合法情况?这并不容易。


1

至少一个空格和至少4个字符(包括空格)

\A(?=.* )[^0-9`!@#\\\$%\^&*\;+_=]{4,}\z

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接