So I have a rails app with a url field for embedding youtube and vimeo videos. Everything works fine but I cannot find a solution to validating both fields but only when one is used.
A user chooses a video url and has a choice of using vimeo or youtube and upon saving I would like to validate that the url code of the video(youtube or vimeo) is correct.
This is what I have
youtube validate code
validates :url ,
:format => {:with => /(https?):\/\/(www.)?(youtube\.com\/watch\?v=|youtu\.be\/)([A-Za-z0-9_-]*)(\&\S+)?.*/}
Vimeo validate code
validates :url ,
:format => {:with => /http:\/\/(www.)?vimeo\.com\/([A-Za-z0-9._%-]*)((\?|#)\S+)?/}
When I have the youtube code I cannot save a vimeo video and vice versa.
Both of the above codes work but only one, how can I have it so both work at the same time?
You could mash your regexes together into one big incomprehensible regex or you could use a custom validation method:
You could also separate your two YouTube patterns with this approach and get code that is easier to read.
And while I’m here, if you’re using a lot of slashes in your regexes you might want to use
%r{}instead: