如何在文本框中验证客户端的YouTube网址 [英] How to validate youtube url in client side in text box

查看:101
本文介绍了如何在文本框中验证客户端的YouTube网址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须创建一个只允许你管视频的文本框。

为了处理服务器端的验证,我使用下面的代码

a>

  $ rx ='〜
^(?:https?://)? #可选协议
(?:www \。)? #可选子域
(?:youtube\.com | youtu\.be)#强制域名
/ watch\?v =([^&] +)#带视频标识的URI作为捕获组1
~x';

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

我一直在为客户端验证寻找相同的解决方案。我找到了< input type =url> 这里但它似乎只适用于html5浏览器。



是否可以使用文本框进行客户端验证,以便与所有浏览器兼容?



谢谢

解决方案

以下是验证YouTube网址的代码 - p>

  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){
//做任何事情都是有效的
//如果需要更改url来嵌入url,然后使用('#ytplayerSide')。attr('src','https://www.youtube.com/embed/'+ match [2] +'?autoplay = 0');
}
else {
//做任何事情都是无效的
}
}
}

小提琴网址
https://jsfiddle.net/cpjushnn/12/


I have to create a text box which only allows you tube url for videos.

To handle the validation in server side, I am using 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);

I was looking for the same solution for client side validation. I found about <input type="url"> here but it seems it is only for html5 browsers.

Is it possible to do client side validation with text box so that it will be compatible with all browser?

Thanks

解决方案

Here is the code which validates the 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/

这篇关于如何在文本框中验证客户端的YouTube网址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆