【问题标题】:Validation of data for certain specific special characters验证某些特定特殊字符的数据
【发布时间】:2011-07-19 10:29:24
【问题描述】:

我想向我的 rails 应用程序添加验证。我已经在我的模型中添加了,

validates_format_of :description, :with => /^[a-zA-Z\d ]*$/i,:message =>
 "can only contain letters and numbers." 

但现在我希望允许一些特定的特殊字符(例如前:)。

如何添加它们?

【问题讨论】:

    标签: ruby-on-rails ruby regex validation


    【解决方案1】:

    只需将它们添加到方括号内的正则表达式中即可。添加冒号:

    /^[a-zA-Z\d :]*$/
    

    但请注意,有一些特殊字符需要使用反斜杠进行转义:. | ( ) [ ] { } + \ ^ $ * ?。要将句点添加到您的集合中,请使用:

    /^[a-zA-Z\d \.]*$/
    

    【讨论】:

      【解决方案2】:

      您可以将它们添加到您拥有的正则表达式中:

      validates_format_of :description, :with => /^[a-zA-Z\d\s:]*$/i,:message =>
       "can only contain letters and numbers."
      

      (我也将正则表达式中的文字空白字符更改为 \s 转义。)

      【讨论】:

        【解决方案3】:

        听起来除了空格和冒号之外,您还想要所有标准单词字符(我知道您没有明确提到下划线):

        /^[\w\s:]*$/

        【讨论】:

          猜你喜欢
          • 2013-05-16
          • 2011-03-09
          • 1970-01-01
          • 2021-09-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多