How do I correctly set up this validation in my model?
When I validate the format of a string, I'll do:
validates :link, :uniqueness => true,
:format => { :with => (regular expression) }
I want the link to be either a youtube video by this regex:
/^http:\/\/www\.youtube\.com\/watch\?v=([a-zA-Z0-9_-]*)/开发者_高级运维
or a vimeo video:
/^http:\/\/www\.vimeo\.com\/(\d+)/
How do I set up this validation in my model?
You could combine those two regular expressions into one, though I presume you mean you have two different expressions instead of two identical ones:
validates :link,
:uniqueness => true,
:format => {
:with => %r[http://(?:www\.youtube\.com/watch\?v=(\w+)|www\.vimeo\.com...)]
}
Using %r[...]
instead of /.../
saves you from having to escape all the slashes.
Also note that YouTube may use a youtu.be
domain, so you may need yet another part to your regular expression. If this thing gets totally out of hand you may want to take a different approach and have a list of regexps you compare it against:
VALID_URLS = [
%r[http://www\.youtube\.com/watch\?v=(\w+)],
%r[http://www\.youtu\.be/(\w+)],
%r[ ... ]
]
Then validate something like this:
validates :link,
:uniqueness => true,
:format => {
:with => Regexp.new(VALID_URLS.join('|'))
}
精彩评论