Rails 验证 full_name [英] Rails validating full_name

查看:39
本文介绍了Rails 验证 full_name的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿...您将如何验证 full_name 字段(姓名姓氏).

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

推荐答案

考虑以下名称:

  • 小姐扬·莱文森-古尔德
  • 博士小马丁路德金
  • Brett d'Arras-d'Haudracey
  • 布鲁诺
  • 您可能只想确保某些字符集存在,而不是验证存在的字符.

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

    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 验证 full_name的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆