嘿...您将如何验证全名字段(姓氏)。
问问题
6527 次
3 回答
32
考虑如下名称:
- Jan Levinson-Gould 女士
- 小马丁路德金博士
- Brett d'Arras-d'Haudracey
- 布鲁诺
您可能只想确保不存在某些字符集,而不是验证那里的字符。
例如:
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 回答
1
至少一个空格和至少4个字符(包括空格)
\A(?=.* )[^0-9`!@#\\\$%\^&*\;+_=]{4,}\z
于 2014-09-27T15:37:35.783 回答