我正在 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/