ruby-on-rails - 用于排除数字或特殊字符的正则表达式

标签 ruby-on-rails ruby regex forms

我正在 Rails 中设置一个需要名字和姓氏的用户表单。我决定使用这个 Ruby doc 中倒数第三个正则表达式以确保他们不输入任何数字或特殊字符。不幸的是,当我返回表单时出现此错误:

The provided regular expression is using multiline anchors (^ or $), which may present a security risk. Did you mean to use \A and \z, or forgot to add the :multiline => true option?.

我刚刚开始学习 RegEx,所以如果有更好的方法来编写此验证,我会洗耳恭听。

代码:

validates :first_name, :last_name, length: {minimum: 2}, format: {with: /^([^\d\W]|[-])*$/, message: 'First Name/Last Name cannot have any numbers or special characters'}

最佳答案

您链接到的文档说明:

Note: use \A and \Z to match the start and end of the string, ^ and $ match the start/end of a line.

由于您不需要名称的多行支持(即名称中的换行符应被视为无效),您可以安全地将其更改为:

/\A([^\d\W]|[-])*\Z/

另见 this answer这更多地解释了安全风险。

关于ruby-on-rails - 用于排除数字或特殊字符的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26256219/

相关文章:

ruby-on-rails - 安装 rails 时出错 : Error building native extension (-Wl insilde ld call)

ruby - 将日期范围缩小为每个月最后几天的数组?

regex - Lua:如何在字符串中的两个或多个重复字符之间放置某些内容?

sql - 跨多对多关系查询

ruby-on-rails - 如何使用 group by 作为 json 嵌套哈希数组?

ruby - 如何获取散列的每个值的大小

ruby-on-rails - 为什么 `posts_path` 在 `rails console` 中不起作用?

php - htaccess 图片 url 重写规则

C++ - 拆分 HTTP header 的正则表达式?

html - 覆盖其他HTML文件的application.html.erb