基于正则表达式的 Rails 自定义验证? [英] Rails custom validation based on a regex?
问题描述
我在 routes.rb 中为/type-in-something-here 使用了以下正则表达式
I have the following regex that I use in my routes.rb for /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
在路线中这很有效:
match ':uuid' => 'room#show', :constraints => { :uuid => /[A-Za-z\d]([-\w]{,498}[A-Za-z\d])?/ }
我也想将此作为验证,以免创建无效记录.所以我在 room.rb 中添加了以下内容:
I want to have this also as a validation so invalid records aren't created. So I added the following to room.rb:
validates_format_of :uuid, :with => /[A-Za-z\d]([-\w]{,498}[A-Za-z\d])?/i, :message => "Invalid! Alphanumerics only."
但是这个 validates_format_of 不起作用,而不是添加错误,而是允许记录保存.
But this validates_format_of isn't working, and instead of adding an error it's allow the record to save.
知道有什么问题吗?
谢谢
推荐答案
为了验证的目的,记得添加字符串标记\A
和\Z
的开始和结束:
For validation purposes, remember to add the beginning and end of string markers \A
and \Z
:
validates_format_of :uuid, :with => /\A[A-Za-z\d]([-\w]{,498}[A-Za-z\d])?\Z/i
否则你的正则表达式会很高兴地匹配任何至少包含一个字母或数字的字符串.出于某种原因,Rails 隐式地在路由中添加了边界.(可能是因为它将正则表达式嵌入到更大的正则表达式中以匹配整个 URL,并显式检查 /
和 URL 的结尾.)
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 自定义验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!