YouTube URL Tricks: Extracting Video IDs and Ensuring Validity in Dart

Mohamed Abdo Elnashar
Flutter UAE
Published in
5 min readSep 23, 2023

A Comprehensive Guide to YouTube URL Manipulation in Dart

You may often need to work with YouTube URLs in your projects. Two common tasks involve extracting YouTube Video IDs from URLs and validating YouTube URLs for accuracy and security. In this article, we will explore how to perform these tasks in Dart.

Section 1: Extracting YouTube Video IDs

YouTube Video IDs are unique identifiers for videos hosted on the platform. They are essential when you need to reference or manipulate specific videos. Dart provides a straightforward way to extract these Video IDs from various types of YouTube URLs.

The Initial Challenge

YouTube URLs come in different formats, including regular video URLs, short URLs, and live stream URLs. Extracting the Video ID from these URLs requires handling each format correctly.

Code Solution

We can achieve Video ID extraction using regular expressions in Dart. Here’s a Dart function that accomplishes this:

String? extractVideoId(String url) {
if (url.contains(' ')) {
return null;
}

late final Uri uri;
try {
uri = Uri.parse(url);
} catch (e) {
return null;
}

if (!['https', 'http'].contains(uri.scheme)) {
return null;
}

// youtube.com/watch?v=xxxxxxxxxxx
if (['youtube.com', 'www.youtube.com', 'm.youtube.com'].contains(uri.host) &&
uri.pathSegments.isNotEmpty &&
(uri.pathSegments.first == 'watch' || uri.pathSegments.first == 'live') &&
uri.queryParameters.containsKey('v')) {
final videoId = uri.queryParameters['v']!;
return _isValidId(videoId) ? videoId : null;
}

// youtu.be/xxxxxxxxxxx
if (uri.host == 'youtu.be' && uri.pathSegments.isNotEmpty) {
final videoId = uri.pathSegments.first;
return _isValidId(videoId) ? videoId : null;
}

// www.youtube.com/shorts/xxxxxxxxxxx
// youtube.com/shorts/xxxxxxxxxxx
if (uri.host == 'www.youtube.com' || uri.host == 'youtube.com') {
final pathSegments = uri.pathSegments;
if (pathSegments.contains('shorts') && pathSegments.length >= 2) {
final videoId = pathSegments.last;
return _isValidId(videoId) ? videoId : null;
}
}

return null;
}

bool _isValidId(String id) => RegExp(r'^[_\-a-zA-Z0-9]{11}$').hasMatch(id);

This code extracts the Video ID from regular video URLs and YouTube Shorts URLs. It employs regular expressions to identify and retrieve the Video ID.

Demonstrating the Code

Let’s see how this code works with some sample URLs:

void main() {
final youtubeUrl = 'https://www.youtube.com/watch?v=N9QSL1PLUS4&ab_channel=%D9%82%D9%86%D8%A9%D8%A7%D9%84%D9%82%D8%B1%D8%A7%D9%86%D8%A7%D9%84%D9%83%D8%B1%D9%8A%D9%85';
final shortsUrl = 'https://youtu.be/hmGb1dTfcFY';
final videoIdFromYoutube = extractVideoId(youtubeUrl);
final videoIdFromShorts = extractVideoId(shortsUrl);
print('Video ID from YouTube URL: $videoIdFromYoutube');
print('Video ID from Shorts URL: $videoIdFromShorts');
}
screenshot for test code

Handling Live Stream URLs

The code provided primarily focuses on regular video URLs and short URLs. To handle live stream URLs, we’ll need to modify the regular expressions. Stay tuned for Section 2, where we refine the Video ID extraction code to include live stream URLs.

Section 2: Refining the Video ID Extraction Code

Live stream URLs on YouTube have a slightly different format than regular video URLs. To ensure that our Video ID extraction code works for live streams as well, we need to make some adjustments.

The Challenge with Live Stream URLs

Live stream URLs typically look like this: ‘https://www.youtube.com/live/N9QSL1PLUS4'. They include additional path segments and query parameters, which our initial code does not handle.

Updated Code Solution

Let’s enhance our code to handle live stream URLs by modifying the check expressions:

  // youtube.com/live/xxxxxxxxxxx
if (['youtube.com', 'www.youtube.com', 'm.youtube.com'].contains(uri.host) &&
uri.pathSegments.isNotEmpty &&
uri.pathSegments.first == 'live' && _isValidId(uri.pathSegments.last)) {
return uri.pathSegments.last;
}

We’ve introduced a new check expression, that matches live stream URLs with the 'live' parameter. This allows us to extract Video IDs from live stream URLs successfully.

screenshot for test code

Section 3: Validating YouTube URLs in Dart

Validating YouTube URLs is essential for ensuring data integrity and security in your Dart applications. Let’s create a function, isValidYouTubeUrl, to validate YouTube URLs using Dart.

The Need for URL Validation

Validating URLs helps prevent invalid or malicious data from entering your application. It ensures that the URLs you work with are legitimate and safe.

URL Validation Code

Here’s a Dart function that validates YouTube URLs:

bool isValidYouTubeUrl(String url) {
late final Uri uri;
try {
uri = Uri.parse(url);
} catch (e) {
return false;
}

if (!['https', 'http'].contains(uri.scheme)) {
return false;
}
// youtube.com/watch?v=xxxxxxxxxxx
if (['youtube.com', 'www.youtube.com', 'm.youtube.com'].contains(uri.host) &&
uri.pathSegments.isNotEmpty &&
(uri.pathSegments.first == 'watch' || uri.pathSegments.first == 'live')) {
return true;
}
// youtu.be/xxxxxxxxxxx
if (uri.host == 'youtu.be' && uri.pathSegments.isNotEmpty) {
return true;
}
// www.youtube.com/shorts/xxxxxxxxxxx
// www.youtube.com/embed/xxxxxxxxxxx
if (uri.host == 'www.youtube.com' &&
uri.pathSegments.length == 2 &&
['shorts', 'embed'].contains(uri.pathSegments.first)) {
return true;
}
return false;
}

This code checks if a given URL matches the expected YouTube URL patterns. If it does, it returns true; otherwise, it returns false.

Demonstrating URL Validation

Let’s test the isValidYouTubeUrl function with different types of YouTube URLs:

void main() {
final url1 = 'https://www.youtube.com/watch?v=VIDEO_ID_HERE';
final url2 = 'https://youtu.be/VIDEO_ID_HERE';
final url3 = 'https://www.youtube.com/shorts/VIDEO_ID_HERE';
final url4 = 'https://www.youtube.com/live/VIDEO_ID_HERE';

print(isValidYouTubeUrl(url1)); // Should return true
print(isValidYouTubeUrl(url2)); // Should return true
print(isValidYouTubeUrl(url3)); // Should return true
print(isValidYouTubeUrl(url4)); // Should return true
}
screenshot for test code

In this article, we’ve explored how to extract YouTube Video IDs and validate YouTube URLs in Dart. We started by extracting Video IDs from regular video and short URLs and then refined our code to handle live stream URLs. We also created a function to validate YouTube URLs, ensuring data integrity and security in your Dart applications.

I hope you all liked this blog and it helped you start with Flutter! Don’t forget to smash that clap button and comment below.

If you liked this article make sure to 👏 it below, and connect with me on Portfolio, Github, and LinkedIn.

Meet you at the next one.

--

--

Mohamed Abdo Elnashar
Flutter UAE

Senior Flutter Developer, and I study a master of computer science in the faculty of computer & information sciences at Mansoura university