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

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

问题描述

我必须创建一个文本框,它只允许您输入视频的 url.

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);

我正在寻找相同的客户端验证解决方案.我发现了关于 <input type="url"> here 但它似乎是仅适用于 html5 浏览器.

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?

谢谢

推荐答案

这是验证 youtube url 的代码-

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
            }
        }
}

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

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

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