I have You-tube embed code field in my form. How I validate that?
Do you want to validate on the user end or on the server end? I once had a form that required this. My solution was to use javascript to insert the embed code directly into the page and therefore allow a user to preview their copy/paste job before finally submitting the form. Facebook pretty much does the same thing when posting a Youtube link.
On the server-side, there are two things that I think could help you: the Youtube API, and the fact that every video on Youtube has a "v" parameter. The API allows for searching by this video id. (Details here: http://code.google.com/apis/youtube/2.0/developers_guide_protocol_video_entries.html)
You would then determine from the API response whether or not that video exists. The only other tricky part might be finding the "v" parameter in the embed code, because I believe the embed code changes from time to time. For instance
... param name="movie" value="http://www.youtube.com/v/5p0QtJMKt1s?version=3" ...
is part of the embed code. And this is the link to that same video on YouTube:
http://www.youtube.com/watch?v=5p0QtJMKt1s
Furthermore if you just pull out the URL from the embed code and paste it in your browser, it actually works as well.
http://www.youtube.com/v/5p0QtJMKt1s
So, in summary, get acquainted with the Youtube API in your language of choice, figure out how to parse the "v" parameter from embed code, and use them together.
If your user is just giving you the video number, then YouTube effectively 'validates' it for you - if the video is invalid YouTube will say so.
I would recommend against allowing the user to enter the entire embed code because they could enter other options that don't make sense for your context.
One way to confirm for your user that they've entered correctly is to render the video right after they type in the embed code so they get instant feedback.
As per me, you can only validate the pattern of embed code, but not that if this code points to some valid video or not.
精彩评论