feat: Add validation for YouTube URL and enhance image upload experience in creator's album editor
This commit is contained in:
64
frontend/src/utils/youtube.js
Normal file
64
frontend/src/utils/youtube.js
Normal file
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* Regular expression for matching YouTube video IDs in various URL formats
|
||||
*/
|
||||
const VIDEO_ID_REGEX = /(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/i;
|
||||
|
||||
/**
|
||||
* Regular expression for matching standalone YouTube video IDs
|
||||
*/
|
||||
const SHORT_URL_REGEX = /^[a-zA-Z0-9_-]{11}$/;
|
||||
|
||||
/**
|
||||
* Extracts the video ID from a YouTube URL or returns the input if it's already a video ID.
|
||||
* @param {string} input - The YouTube URL or video ID
|
||||
* @returns {string|null} The extracted video ID or null if invalid
|
||||
*/
|
||||
export function extractVideoId(input) {
|
||||
if (!input) return null;
|
||||
|
||||
// If it's already a valid video ID, return it
|
||||
if (isValidVideoId(input)) {
|
||||
return input;
|
||||
}
|
||||
|
||||
// Try to extract video ID from URL
|
||||
const match = input.match(VIDEO_ID_REGEX);
|
||||
return match ? match[1] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates if the input is a valid YouTube video ID.
|
||||
* @param {string} input - The video ID to validate
|
||||
* @returns {boolean} True if the input is a valid video ID
|
||||
*/
|
||||
export function isValidVideoId(input) {
|
||||
if (!input) return false;
|
||||
return SHORT_URL_REGEX.test(input);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates if the input is a valid YouTube URL or video ID.
|
||||
* @param {string} input - The URL or video ID to validate
|
||||
* @returns {boolean} True if the input is a valid YouTube URL or video ID
|
||||
*/
|
||||
export function isValidYouTubeUrlOrId(input) {
|
||||
if (!input) return false;
|
||||
|
||||
// Check if it's a valid video ID
|
||||
if (isValidVideoId(input)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Check if it's a valid YouTube URL
|
||||
return VIDEO_ID_REGEX.test(input);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a YouTube embed URL from a video ID.
|
||||
* @param {string} videoId - The YouTube video ID
|
||||
* @returns {string} The YouTube embed URL
|
||||
*/
|
||||
export function buildEmbedUrl(videoId) {
|
||||
if (!videoId) return '';
|
||||
return `https://www.youtube.com/embed/${videoId}`;
|
||||
}
|
||||
Reference in New Issue
Block a user