Railsvalidationfull_name

嘿……你如何validation一个full_name字段(名字姓氏)。

考虑如下名称:

  • Jan Levinson-Gould女士
  • 小马丁·路德金博士
  • Brett d’Arras-d’Haudracey
  • 布鲁诺

您可能只想确保存在某些字符集,而不是validation那里的字符。

例如:

 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 

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

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

您在此处执行的任何validation都可能会崩溃,除非它非常笼统。 例如,强制执行最小长度为3可能与您可以获得的结果一样合理,而无需了解输入的内容。

当你的名字如“O’Malley”与撇号,“史密斯 – 约翰逊”与短划线,“Andrés”与重音字符或极短的名称,如“Vo Ly”几乎没有字符,你如何validation不排除合法案件? 这是不容易的。