regex 如何在文本框中验证客户端中的YouTube URL

7ivaypg9  于 2023-11-20  发布在  其他
关注(0)|答案(6)|浏览(130)

我必须创建一个文本框,只允许你管视频的网址。
为了在服务器端处理验证,我使用below code

$rx = '~
    ^(?:https?://)?              # Optional protocol
     (?:www\.)?                  # Optional subdomain
     (?:youtube\.com|youtu\.be)  # Mandatory domain name
     /watch\?v=([^&]+)           # URI with video id as capture group 1
     ~x';

$has_match = preg_match($rx, $url, $matches);

字符串
我正在寻找客户端验证的相同解决方案。我找到了<input type="url">here,但似乎它只适用于html5浏览器。
是否可以使用文本框进行客户端验证,以便与所有浏览器兼容?
谢谢

jvidinwx

jvidinwx1#

下面是验证youtube url的代码-

function validateYouTubeUrl()
{
    var url = $('#youTubeUrl').val();
        if (url != undefined || url != '') {
            var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=|\?v=)([^#\&\?]*).*/;
            var match = url.match(regExp);
            if (match && match[2].length == 11) {
                // Do anything for being valid
                // if need to change the url to embed url then use below line
                $('#ytplayerSide').attr('src', 'https://www.youtube.com/embed/' + match[2] + '?autoplay=0');
            }
            else {
                // Do anything for not being valid
            }
        }
}

字符串

Fiddle URL:https://jsfiddle.net/cpjushnn/12/

sg3maiej

sg3maiej2#

请看这个工作示例:

function matchYoutubeUrl(url) {
    var p = /^(?:https?:\/\/)?(?:m\.|www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;
    if(url.match(p)){
        return url.match(p)[1];
    }
    return false;
}

字符串
小提琴:http://jsfiddle.net/3ouq9u3v/13/

ru9i0ody

ru9i0ody3#

**再次更新此.(再次07/September/2022)**正如我所看到的,有7个场景,以满足我到目前为止已经确定(我编造了这些名字):
普通网址

1.第一个月

分享网址

  1. https://youtu.be/12345678901

带开始时间的共享URL

  1. https://youtu.be/12345678901?t=6

移动的浏览器url

  1. https://m.youtube.com/watch?v=12345678901&list=RD12345678901&start_radio=1

长URL

  1. https://www.youtube.com/watch?v=12345678901&list=RD12345678901&start_radio=1&rv=smKgVuS

带开始时间的长url

  1. https://www.youtube.com/watch?v=12345678901&list=RD12345678901&start_radio=1&rv=12345678901&t=38

Youtube短片

  1. https://youtube.com/shorts/12345678901
    我最初提供了一个基于Jitendras答案的扩展答案,因为它似乎有一些差距。例如,对于较短的共享URL,如https://youtu.be/abcdefgh_ij,如果您在末尾添加字符,Jitendras不会捕获它。此外,如果用户在文本字段中删除了错误,则不会删除该值。
    然而,我假设原始发帖者实际上想在iframe嵌入中使用URL,这里的答案都不适用。嵌入的URL格式不同,需要处理。
    下面是我正在做的事情,接受用户输入,验证它,用一个正确格式的可嵌入URL替换它,然后将它分配给一个iframe以显示在UI上。
    注意事项:下面将处理所有上述,但它不会显示所有上述.即它会格式化一个起始时间的网址嵌入它,但你会失去起始时间.但一个小的自定义我相信你可以处理.
    可能对某些人有好处....
function validateVideoLinkTitle() {

    document.getElementById('TitleImageUrl').value = null;
    document.getElementById('TitleImageValidationField').value = null;
    document.getElementById('CardDynamicImage').src = '/images/cardimage.png';

    var ArticleTitleVideoField = document.getElementById("ArticleTitleVideoField");
    var VideoLinkText = ArticleTitleVideoField.value;
    var ArticleTitleVideoValidation = document.getElementById("ArticleTitleVideoValidation");
    var ArticleTitleImageSizeValidation = document.getElementById("ArticleTitleImageSizeValidation");
    ArticleTitleImageSizeValidation.style.display = 'none';
    var ArticleTitleImageTypeValidation = document.getElementById("ArticleTitleImageTypeValidation");
    ArticleTitleImageTypeValidation.style.display = 'none';
    var CardDynamicImageDiv = document.getElementById("CardDynamicImageDiv");
    CardDynamicImageDiv.style.display = 'none';
    var CardDynamicVideoDiv = document.getElementById("CardDynamicVideoDiv");
    CardDynamicVideoDiv.style.display = 'block';

    var urlType = 0;

    if ((VideoLinkText.includes("watch?v=") || VideoLinkText.includes("https://m.youtube") || VideoLinkText.includes("watch?app=desktop&v=")) && !VideoLinkText == "") {
        urlType = 1;
    } else if ((VideoLinkText.includes("embed") && !VideoLinkText == "")) {
        urlType = 2;
    } else if ((VideoLinkText.includes("tu.be") && !VideoLinkText == "")) {
        urlType = 3;
    }
    console.log('title urlType:' + urlType);

    switch (urlType) {
        case 1:
            var endOfString = VideoLinkText.split(/=(.*)/)[1];
            var stringLength = endOfString.length;
            console.log('title stringLength 1: ' + stringLength);

            var p = /^(?:https?:\/\/)?(?:m\.|www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;
            if (!VideoLinkText.match(p)) {
                ArticleTitleVideoValidation.style.display = 'block';
                $("#TitleImageValidationField").val("");
                document.getElementById('CardDynamicVideo').src = '';
                CardDynamicImageDiv.style.display = 'block';
                CardDynamicVideoDiv.style.display = 'none';
            } else {
                ArticleTitleVideoValidation.style.display = 'none';
                $("#TitleImageValidationField").val("Ok");
                console.log("title VideoLinkText 1: " + VideoLinkText)
                var processedUrl = titleProcessVideoUrl(VideoLinkText, true);
                document.getElementById('CardDynamicVideo').src = processedUrl;
                $("#ArticleTitleVideoField").val(processedUrl);
            }

            if (stringLength > 11) {
                ArticleTitleVideoValidation.style.display = 'block';
                $("#TitleImageValidationField").val("");
                document.getElementById('CardDynamicVideo').src = '';
                CardDynamicImageDiv.style.display = 'block';
                CardDynamicVideoDiv.style.display = 'none';
            }
            break;
        case 2:
            var endOfString = VideoLinkText.split('/')[4];
            var p = /^(?:https?:\/\/)?(?:m\.|www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;

            if (VideoLinkText.includes("https://www.") && VideoLinkText.match(p)) {
                stringLength = endOfString.length;
                console.log('title stringLength 2: ' + stringLength);
            } else {
                VideoLinkText = titleProcessVideoUrl(VideoLinkText, true);
                if (VideoLinkText.match(p)) {
                    var endOfString = VideoLinkText.split('/')[4];
                    stringLength = endOfString.length;
                    console.log("new VideoLinkText: " + VideoLinkText)
                }
            }
            console.log('title stringLength 3: ' + stringLength);

            if (!VideoLinkText.match(p)) {
                console.log('VideoLinkText !match(p): ' + VideoLinkText);
                ArticleTitleVideoValidation.style.display = 'block';
                $("#TitleImageValidationField").val("");
                document.getElementById('CardDynamicVideo').src = '';
                CardDynamicImageDiv.style.display = 'block';
                CardDynamicVideoDiv.style.display = 'none';
            } else {
                ArticleTitleVideoValidation.style.display = 'none';
                $("#TitleImageValidationField").val("Ok");
                console.log("title VideoLinkText 2: " + VideoLinkText)
                var processedUrl = titleProcessVideoUrl(VideoLinkText, true);
                document.getElementById('CardDynamicVideo').src = processedUrl;
                $("#ArticleTitleVideoField").val(processedUrl);
            }

            if (stringLength > 11) {
                console.log('stringLength > 11 if block');
                ArticleTitleVideoValidation.style.display = 'block';
                $("#TitleImageValidationField").val("");
                document.getElementById('CardDynamicVideo').src = '';
                CardDynamicImageDiv.style.display = 'block';
                CardDynamicVideoDiv.style.display = 'none';
            }
            break;
        case 3:
            var endOfString = VideoLinkText.split('/')[3];
            var p = /^(?:https?:\/\/)?(?:m\.|www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;

            if (VideoLinkText.includes("https://youtu.be/") && VideoLinkText.match(p)) {
                stringLength = endOfString.length;
                console.log('title stringLength 4: ' + stringLength);
            } else {
                VideoLinkText = titleProcessVideoUrl(VideoLinkText, true);
                if (VideoLinkText.match(p)) {
                    var endOfString = VideoLinkText.split('/')[3];
                    stringLength = endOfString.length;
                    console.log("new VideoLinkText: " + VideoLinkText)
                }
            }
            console.log('title stringLength 5: ' + stringLength);
            if (!VideoLinkText.match(p)) {
                console.log('VideoLinkText !match(p) 1: ' + VideoLinkText);
                ArticleTitleVideoValidation.style.display = 'block';
                $("#TitleImageValidationField").val("");
                document.getElementById('CardDynamicVideo').src = '';
                CardDynamicImageDiv.style.display = 'block';
                CardDynamicVideoDiv.style.display = 'none';
            } else {
                ArticleTitleVideoValidation.style.display = 'none';
                $("#TitleImageValidationField").val("Ok");
                document.getElementById('CardDynamicVideo').src = VideoLinkText;
                console.log("title VideoLinkText 3: " + VideoLinkText)
                var processedUrl = titleProcessVideoUrl(VideoLinkText, false);
                document.getElementById('CardDynamicVideo').src = processedUrl;
                $("#ArticleTitleVideoField").val(processedUrl);
            }

            if (stringLength > 11) {
                console.log('stringLength > 11 if block 1');
                ArticleTitleVideoValidation.style.display = 'block';
                $("#TitleImageValidationField").val("");
                document.getElementById('CardDynamicVideo').src = '';
                CardDynamicImageDiv.style.display = 'block';
                CardDynamicVideoDiv.style.display = 'none';
            }
            break;
        default:
            console.log('title default');
            var p = /^(?:https?:\/\/)?(?:m\.|www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;
            if (!VideoLinkText.match(p) && !VideoLinkText == "") {
                console.log('VideoLinkText !match(p) 2: ' + VideoLinkText);
                ArticleTitleVideoValidation.style.display = 'block';
                $("#TitleImageValidationField").val("");
                document.getElementById('CardDynamicVideo').src = '';
                CardDynamicImageDiv.style.display = 'block';
                CardDynamicVideoDiv.style.display = 'none';
            } else {
                ArticleTitleVideoValidation.style.display = 'none';
                $("#TitleImageValidationField").val("");
                var CardDynamicImageDiv = document.getElementById("CardDynamicImageDiv");
                CardDynamicImageDiv.style.display = 'block';
                var CardDynamicVideoDiv = document.getElementById("CardDynamicVideoDiv");
                CardDynamicVideoDiv.style.display = 'none';
            }
    }
}

字符串
...

function titleProcessVideoUrl(rawUrl, notShortSharingUrl) {

    if (notShortSharingUrl) {

        console.log('rawUrl 1: ' + rawUrl)

        if (!rawUrl.includes("https://") && rawUrl.includes("http://")) {
            rawUrl = rawUrl.replace('http://', 'https://')
            console.log('rawUrl 2: ' + rawUrl)
        } else if (!rawUrl.includes("https://") && rawUrl.includes("www.") && !rawUrl.includes("youtu.be")) {
            rawUrl = rawUrl.replace('www.', 'https://www.')
            console.log('rawUrl 3: ' + rawUrl)
        } else if (rawUrl.includes("https://") && !rawUrl.includes("www.") && !rawUrl.includes("youtu.be")) {
            rawUrl = rawUrl.replace('https://', 'https://www.')
            console.log('rawUrl 4: ' + rawUrl)
        } else if (rawUrl.includes("youtube.com/") && !rawUrl.includes("https://") && !rawUrl.includes("http://")) {
            rawUrl = rawUrl.replace('youtube.com/', 'https://www.youtube.com/')
            console.log('rawUrl 5: ' + rawUrl)
        } else if (rawUrl.includes("youtu.be/") && !rawUrl.includes("https://") && !rawUrl.includes("http://") && !rawUrl.includes("www.")) {
            rawUrl = rawUrl.replace('youtu.be/', 'https://youtu.be/')
            console.log('rawUrl 6: ' + rawUrl)
        } else if (rawUrl.includes("youtu.be/") && !rawUrl.includes("https://") && rawUrl.includes("http://")) {
            rawUrl = rawUrl.replace('http://', 'https://')
            console.log('rawUrl 7: ' + rawUrl)
        } else if (rawUrl.includes("https://") && rawUrl.includes("www.youtu.be/")) {
            rawUrl = rawUrl.replace('www.youtu.be/', 'youtu.be/')
            console.log('rawUrl 8: ' + rawUrl)
        } else if (!rawUrl.includes("https://") && rawUrl.includes("www.youtu.be/")) {
            rawUrl = rawUrl.replace('www.youtu.be/', 'https://youtu.be/')
            console.log('rawUrl 9: ' + rawUrl)
        }

        console.log('rawUrl 10: ' + rawUrl)

        var processed = rawUrl.replace('watch?v=', 'embed/')
        if (processed.includes("https://m.youtube")) {
            processed = rawUrl.replace('m.youtube', 'www.youtube');
            if (processed.includes("&list=")) {
                processed = processed.split('&list=')[0];
                return processed;
                console.log('title Processed 1: ' + processed);
            }
        } else if (processed.includes("watch?app=desktop&v=")) {
            processed = rawUrl.replace('watch?app=desktop&v=', 'embed/');
            if (processed.includes("&list=")) {
                processed = processed.split('&list=')[0];
                return processed;
                console.log('title Processed 1a: ' + processed);
            }
        } else if (processed.includes("&list=")) {
            processed = processed.split('&list=')[0];
            return processed;
            console.log('title Processed 1b: ' + processed);
        }
        console.log('title Processed 2: ' + processed);
        return processed;
    } else {
        console.log('rawUrl 1:' + rawUrl)
        if (!rawUrl.includes("https://") && rawUrl.includes("http://")) {
            rawUrl = rawUrl.replace('http://', 'https://')
            console.log('rawUrl 2:' + rawUrl)
        } else if (!rawUrl.includes("https://") && rawUrl.includes("www.")) {
            rawUrl = rawUrl.replace('www.', 'https://www.')
            console.log('rawUrl 3:' + rawUrl)
        }
        console.log('rawUrl 4:' + rawUrl)
        var processed = rawUrl.replace('https://youtu.be/', 'https://www.youtube.com/embed/')
        if (processed.includes("?t=")) {
            processed = processed.split('?t=')[0];
            return processed;
        }

        console.log('title Processed 3: ' + processed);
        return processed;
    }

**注1:**我知道上面的内容并不漂亮。我还没有时间整理它,去掉所有的“如果”,但希望它提供了足够的背景,是有用的
**注2:**请注意您使用的视频。YouTube不允许嵌入具有版权背景音乐的视频,它们将显示为不可用。

lkaoscv7

lkaoscv74#

结合这里的答案和一些修改,我得出了这个正则表达式:

^(?:https?:\/\/)?(?:m\.|www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(\?\S*)?$

字符串
这将匹配任何格式,但将不匹配,如果id长于11个字符。也可以添加开始视频标签与“?”部分结束。
你可以通过粘贴into this来测试它

wnavrhmk

wnavrhmk5#

转义正则表达式中的所有正斜杠,然后将修改后的正则表达式放在/中,不带任何空格或注解行,也不需要添加x修饰符。

var re = /^(?:https?:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/watch\?v=([^&]+)/m;

字符串

bf1o4zei

bf1o4zei6#

Credits:RegEx:摘自this post Variations of YT urls摘自:@DMur's post
正则表达式

const youtubeRegEx = new RegExp(/^(?:https?:\/\/)?(?:m\.|www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|shorts\/|watch\?.+&v=))((\w|-){11})(?:\S+)?$/);

字符串
支持以下URL格式

/**
 * Normal Url: https://www.youtube.com/watch?v=12345678901
 * Share Url: https://youtu.be/12345678901
 * Share Url with start time: https://youtu.be/12345678901?t=6
 * Mobile browser url: https://m.youtube.com/watch?v=12345678901&list=RD12345678901&start_radio=1
 * Long url: https://www.youtube.com/watch?v=12345678901&list=RD12345678901&start_radio=1&rv=smKgVuS
 * Long url with start time: https://www.youtube.com/watch?v=12345678901&list=RD12345678901&start_radio=1&rv=12345678901&t=38
 * Youtube Shorts: https://youtube.com/shorts/12345678901
 */


但要小心,这是不完美的,特别是在视频id后,你可以添加任何东西
你可以查here

相关问题