Rails validating full_name

江枫思渺然 提交于 2019-12-03 07:38:25

问题


Hey... how would you validate a full_name field (name surname).


回答1:


Consider names like:

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

Instead of validating the characters that are there, you might just want to ensure some set of characters is not present.

For example:

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

Tests

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

Regular expression explanation

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



回答2:


Any validation you perform here is likely to break down unless it is extremely general. For instance, enforcing a minimum length of 3 is probably about as reasonable as you can get without getting into the specifics of what is entered.

When you have names like "O'Malley" with an apostrophe, "Smith-Johnson" with a dash, "Andrés" with accented characters or extremely short names such as "Vo Ly" with virtually no characters at all, how do you validate without excluding legitimate cases? It's not easy.




回答3:


At least one space and at least 4 char (including the space)

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


来源:https://stackoverflow.com/questions/2629422/rails-validating-full-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!