I’m using regexs to embed a youtube video into my app. The video is provided by the user and I want to validate this input before it gets stored in the database. I’m trying to use the same regexs to do that but running into some issues. My intended functionality is for the validation to be true if one of the regexs match.
validates_format_of :video_link, :with => /youtu\.be\/([^\?]*)/ || /^.*((v\/)|(embed\/)|(watch\?))\??v?=?([^\&\?]*).*/
this is what I thought would work but it’s not, it denies everything ive input so far
validates_format_of :video_link, :with => /youtu\.be\/([^\?]*)/ && /^.*((v\/)|(embed\/)|(watch\?))\??v?=?([^\&\?]*).*/
This is what I have now and it’s working (without errors as far as I can tell). I thought that this wouldn’t work because both regexs would have to match for the validation to pass. Why is this happening? Thanks in advance.
This expression:
evaluates to the first regex because a regex object is true in a boolean context, so this:
is equivalent to this:
This expression:
evaluates to the second regex so this:
is equivalent to this:
I think you just want to combine the two regexes into one with an alternation operator:
You might also consider skipping the regex validator in favor or a simple Ruby method that uses
URI.parseto pull the URL apart, then you could check the hostname, path, and CGI parameters individually without trying to jam it all into a regex.