Rails validating full_name

前端 未结 3 1468
予麋鹿
予麋鹿 2021-02-03 11:54

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

3条回答
  •  旧时难觅i
    2021-02-03 12:31

    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
    

提交回复
热议问题