基于正则表达式的Rails自定义验证?

时间:2022-10-14 21:45:43

I have the following regex that I use in my routes.rb for /type-in-something-here

我有以下正则表达式,我在我的routes.rb中使用/ type-in​​-something-here

# A-Z, a-z, 0-9, _ in the middle but never starting or ending in a _
# At least 5, no more than 500 characters

In the routes this works well as:

在路线中,这适用于:

match ':uuid' => 'room#show', :constraints => { :uuid => /[A-Za-z\d]([-\w]{,498}[A-Za-z\d])?/ }

I want to have this also as a validation so invalid records aren't created. So I added the following to room.rb:

我想将此作为验证,因此不会创建无效记录。所以我在room.rb中添加了以下内容:

validates_format_of :uuid, :with => /[A-Za-z\d]([-\w]{,498}[A-Za-z\d])?/i, :message => "Invalid! Alphanumerics only."

But this validates_format_of isn't working, and instead of adding an error it's allow the record to save.

但是这个validates_format_of不起作用,而不是添加错误,它允许记录保存。

Any ideas what's wrong?

有什么想法有什么不对吗?

Thanks

谢谢

3 个解决方案

#1


16  

For validation purposes, remember to add the beginning and end of string markers \A and \Z:

出于验证目的,请记住添加字符串标记\ A和\ Z的开头和结尾:

validates_format_of :uuid, :with => /\A[A-Za-z\d]([-\w]{,498}[A-Za-z\d])?\Z/i

Otherwise your regex will happily match any string that contains at least a letter or a digit. For some reason Rails implicitly adds the boundaries in the routes. (Probably because it embeds the regex inside a larger one to match the entire URL, with explicit checks for / and the end of the URL.)

否则,你的正则表达式将很乐意匹配任何至少包含字母或数字的字符串。出于某种原因,Rails隐含地添加了路由中的边界。 (可能是因为它将正则表达式嵌入到一个较大的内容中以匹配整个URL,并显式检查/和URL的结尾。)

#2


10  

using something like this

使用这样的东西

validates :uuid, :format => {:with => /[A-Za-z\d]([-\w]{,498}[A-Za-z\d])?/i},
                 :message => "your message"

For more check this

有关更多信息,请查看

#3


4  

validates :name, format: { with: /\A[a-zA-Z]+\z/,
message: "Only letters are allowed" }

#1


16  

For validation purposes, remember to add the beginning and end of string markers \A and \Z:

出于验证目的,请记住添加字符串标记\ A和\ Z的开头和结尾:

validates_format_of :uuid, :with => /\A[A-Za-z\d]([-\w]{,498}[A-Za-z\d])?\Z/i

Otherwise your regex will happily match any string that contains at least a letter or a digit. For some reason Rails implicitly adds the boundaries in the routes. (Probably because it embeds the regex inside a larger one to match the entire URL, with explicit checks for / and the end of the URL.)

否则,你的正则表达式将很乐意匹配任何至少包含字母或数字的字符串。出于某种原因,Rails隐含地添加了路由中的边界。 (可能是因为它将正则表达式嵌入到一个较大的内容中以匹配整个URL,并显式检查/和URL的结尾。)

#2


10  

using something like this

使用这样的东西

validates :uuid, :format => {:with => /[A-Za-z\d]([-\w]{,498}[A-Za-z\d])?/i},
                 :message => "your message"

For more check this

有关更多信息,请查看

#3


4  

validates :name, format: { with: /\A[a-zA-Z]+\z/,
message: "Only letters are allowed" }