Ruby on rails - ActiveRecord Validations 允许空格



我正在使用正则表达式验证模型:

class User < ActiveRecord::Base
  EMAIL_REGEX = /A[w+-.]+@[a-zd-.]+.[a-z]+z/i
  USER_REGEX = /[-w]/i
  validates :name,  presence: true, length: { maximum: 16 }, format: { with: USER_REGEX }
  validates :email, presence: true, uniqueness: true, format: { with: EMAIL_REGEX }
end

但是,未正确验证 :名称字段。如果我进入"rails 控制台"并创建 User 类的新实例,我可以将 :name 设置为包含空格和 .valid?仍然返回 true。如果我在 irb 中测试正则表达式,它不匹配任何空格。

演示:

$ rails c --sandbox
...
2.0.0-p451 :001 > u = User.new name: "hello world", email: "test@example.com"
2.0.0-p451 :002 > u.valid?
  User Exists (0.2ms)  SELECT 1 AS one FROM "users" WHERE "users"."email" = 'test@example.com' LIMIT 1
 => true

我在Linux上使用Ruby 2.0.0-p451,rails 4.0.4。

您的正则表达式未锚定,并且没有量词。 /[-w]/i匹配具有与正则表达式匹配的任何字符的任何字符串。

正确的正则表达式是...

USER_REGEX = /A[-w]+Z/i

这将匹配字符串的开头(A),后跟一个或多个[-w]实例(+是量词),然后是字符串的结尾(Z)。锚点至关重要;它们导致正则表达式匹配整个字符串,或者什么都不匹配。

最新更新