【问题标题】:validate dots and comma with regex ruby 1.9.2使用正则表达式 ruby​​ 1.9.2 验证点和逗号
【发布时间】:2012-02-14 07:02:46
【问题描述】:

我的模型帖子中有这个正则表达式:

validates_format_of :description, :username, :with => /^(?:[^\W_]|\s)*$/u, :message => "should only contain letters, numbers, or .,-_@"

但是这个正则表达式不允许点“.”和逗号“,”。

我希望允许将此字符添加到此正则表达式中。

我怎样才能让这个正则表达式在 username 或 textareas 等字段中正常工作,以验证字母、数字、逗号、点...等

【问题讨论】:

  • 请注意,在 Ruby 中,^$ 表示“行首”和“行尾”,而不是“字符串开头”和“字符串结尾”;所以你的正则表达式实际上匹配任何包含至少一行只有字母和数字和空格的字符串。
  • @ruakh 所说的很重要,您需要使用 \A\Z 锚定到字符串的开头和结尾

标签: ruby-on-rails ruby regex activerecord validation


【解决方案1】:
validates_format_of :description, :username, :with => /^(?:[^\W_]|\s|[\.,_@])*$/u, :message => "should only contain letters, numbers, or .,-_@"

【讨论】:

  • 请注意,这个正则表达式可以大大简化:它相当于/^[\w\s.,@]*$/u
  • 并且应该用\A\z锚定。
猜你喜欢
  • 1970-01-01
  • 2021-08-26
  • 1970-01-01
  • 1970-01-01
  • 2021-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多