Validation de L'URL Youtube de jQuery avec regex

je sais qu'il y a beaucoup de questions répondues ici https://stackoverflow.com/questions/tagged/youtube+regex , mais ne peut pas trouver une question semblable à moi.

tout corps a L'expression régulière JavaScript pour valider la ligne de L'URL de la vidéo YouTube ci-dessous énumérés. Je veux juste savoir où une telle URL peut être possible

http://www.youtube.com/watch?v=bQVoAWSP7k4
http://www.youtube.com/watch?v=bQVoAWSP7k4&feature=popular
http://www.youtube.com/watch?v=McNqjYiFmyQ&feature=related&bhablah
http://youtube.com/watch?v=bQVoAWSP7k4

-- mise à jour 1-- -- mise à jour 2 --

celui-ci a fonctionné presque bien, mais échoué pour L'URL http://youtube.com/watch?v=bQVoAWSP7k4

var matches = $('#videoUrl').val().match(/http://(?:www.)?youtube.*watch?v=([a-zA-Z0-9-_]+)/);
if (matches) {
    alert('valid');
} else {
    alert('Invalid');
}
37
demandé sur Community 2010-06-03 13:31:52

7 réponses

^http:\/\/(?:www\.)?youtube.com\/watch\?v=\w+(&\S*)?$

//if v can be anywhere in the query list

^http:\/\/(?:www\.)?youtube.com\/watch\?(?=.*v=\w+)(?:\S+)?$
20
répondu Amarghosh 2010-06-03 10:12:37

ULTIMATE YOUTUBE REGEX

cueillette de cerises

parce que l'explication est de plus en plus longue, je place le résultat final au sommet. N'hésitez pas à copier+coller, et continuez votre chemin. Pour une explication détaillée, lire "l'histoire complète" ci-dessous.

/**
 * JavaScript function to match (and return) the video Id 
 * of any valid Youtube Url, given as input string.
 * @author: Stephan Schmitz <eyecatchup@gmail.com>
 * @url: https://stackoverflow.com/a/10315969/624466
 */
function ytVidId(url) {
  var p = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;
  return (url.match(p)) ? RegExp. : false;
}

L'histoire complète

Amarghosh de la regex semble bon, à première vue. Mais it:

  1. ne correspond pas à la vidéo id inclure des tirets (-),
  2. ne valide pas la longueur de l'id ( v=aa et v=aaaaaaaaaaaaaaaaaa pour être valide),
  3. et ne correspond pas du tout aux URLs sécurisées (http s : //youtube.com/watch?valid_params)

pour correspondre à https, le caractère dash, et pour valider la longueur d'id, c'était ma suggestion initiale d'un version modifiée du regex D'Amarghosh:

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

mise à jour 1: URLs versus Strings

après avoir posté le modèle ci-dessus, on m'a demandé: "et si URL est comme ceci;

youtube.com/watch?gl=US&hl=en-US&v=bQVoAWSP7k4 "
?

tout d'abord, s'il vous plaît noter que ce n'est pas un URL du tout. RFC URLs conformes doit commencer avec le régime! ;)

de toute façon, pour correspondre à n'importe quelle sorte de chaîne de caractères qui indique de se référer à une vidéo YouTube, j'ai mis à jour ma réponse pour exclure le schéma D'URL étant requis. Ma deuxième suggestion était donc la suivante:

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

mise à JOUR 2: L'ultime expression rationnelle

puis on m'a demandé d'ajouter un support pour un "cas spécial"; le youtu.be url courtes. Au départ, je ne les ai pas ajoutés, car cela ne faisait pas spécifiquement partie de la question. Cependant j'ai mis à jour ma réponse maintenant avec tous possible "cas spéciaux" . Cela signifie que non seulement j'ai ajouté le soutien pour youtu.être des liens, mais aussi les chemins de requête "/v" et "/ embed".

Donc, puis-je vous présenter: Mon dernier et ultime Youtube regex:

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

quelles cordes correspondent?

maintenant Ce modèle fonctionnera pour toutes les chaînes, formaté comme suit:

sans schéma et sous-domaine (domaine: youtu.be, Path:/)

youtu.be/<video:id>   

sans schéma, avec sous-domaine (domaine: youtu.be, Path:/)

www.youtu.be/<video:id>     

avec Schéma HTTP, sans sous-domaine (domaine: youtu.be, Chemin:/)

http://youtu.be/<video:id>   

avec Schéma HTTP et sous-domaine (domaine: youtu.be, Path:/)

http://www.youtu.be/<video:id>   

Avec HTTPS régime, sans sous-domaine (Domaine: youtu.être, Path: /)

https://youtu.be/<video:id>     

Avec HTTPS régime et sous-domaine (Domaine: youtu.être, Path: /)

https://www.youtu.be/<video:id>   

sans régime et sous-domaine (domaine: youtube.com, chemin: / embed)

youtube.com/embed/<video:id>   
youtube.com/embed/<video:id>&other_params 

sans schéma, avec sous-domaine (domaine: youtube.com, chemin: / embed)

www.youtube.com/embed/<video:id>   
www.youtube.com/embed/<video:id>&other_params   

avec Schéma HTTP, sans sous-domaine (domaine: youtube.com, chemin: / embed)

http://youtube.com/embed/<video:id>   
http://youtube.com/embed/<video:id>&other_params  

avec Schéma HTTP et sous-domaine (domaine: youtube.com, chemin: / embed)

http://www.youtube.com/embed/<video:id>   
http://www.youtube.com/embed/<video:id>&other_params  

avec Schéma HTTPS, sans sous-domaine (domaine: youtube.com, chemin: / embed)

https://youtube.com/embed/<video:id>   
https://youtube.com/embed/<video:id>&other_params    

Avec HTTPS régime et sous-domaine (Domaine: youtube.com, Chemin d'accès: /embed)

https://www.youtube.com/embed/<video:id>   
https://www.youtube.com/embed/<video:id>&other_params

sans schéma et sous-domaine (domaine: youtube.com, chemin: / v)

youtube.com/v/<video:id>   
youtube.com/v/<video:id>&other_params 

sans régime, avec sous-domaine (Domain: youtube.com, chemin: / v)

www.youtube.com/v/<video:id>   
www.youtube.com/v/<video:id>&other_params   

avec Schéma HTTP, sans sous-domaine (domaine: youtube.com, chemin: / v)

http://youtube.com/v/<video:id>   
http://youtube.com/v/<video:id>&other_params  

avec Schéma HTTP et sous-domaine (domaine: youtube.com, chemin: / v)

http://www.youtube.com/v/<video:id>   
http://www.youtube.com/v/<video:id>&other_params  

avec Schéma HTTPS, sans sous-domaine (domaine: youtube.com, chemin: / v)

https://youtube.com/v/<video:id>   
https://youtube.com/v/<video:id>&other_params    

Avec HTTPS régime et sous-domaine (Domaine: youtube.com, Chemin d'accès: /v)

https://www.youtube.com/v/<video:id>   
https://www.youtube.com/v/<video:id>&other_params   

sans schéma et sous-domaine (domaine: youtube.com, chemin: /montre)

youtube.com/watch?v=<video:id>   
youtube.com/watch?v=<video:id>&other_params   
youtube.com/watch?other_params&v=<video:id> 
youtube.com/watch?other_params&v=<video:id>&more_params  

sans schéma, avec sous-domaine (domaine: youtube.com, chemin: /montre)

www.youtube.com/watch?v=<video:id>   
www.youtube.com/watch?v=<video:id>&other_params   
www.youtube.com/watch?other_params&v=<video:id>  
www.youtube.com/watch?other_params&v=<video:id>&more_params   

avec Schéma HTTP, sans sous-domaine (Domaine: youtube.com, chemin: /montre)

http://youtube.com/watch?v=<video:id>   
http://youtube.com/watch?v=<video:id>&other_params   
http://youtube.com/watch?other_params&v=<video:id>   
http://youtube.com/watch?other_params&v=<video:id>&more_params  

avec Schéma HTTP et sous-domaine (domaine: youtube.com, chemin: /montre)

http://www.youtube.com/watch?v=<video:id>   
http://www.youtube.com/watch?v=<video:id>&other_params   
http://www.youtube.com/watch?other_params&v=<video:id>   
http://www.youtube.com/watch?other_params&v=<video:id>&more_params  

avec Schéma HTTPS, sans sous-domaine (domaine: youtube.com, chemin: /montre)

https://youtube.com/watch?v=<video:id>   
https://youtube.com/watch?v=<video:id>&other_params   
https://youtube.com/watch?other_params&v=<video:id>   
https://youtube.com/watch?other_params&v=<video:id>&more_params     

Avec HTTPS régime et sous-domaine (Domaine: youtube.com, Chemin d'accès: /watch)

https://www.youtube.com/watch?v=<video:id>   
https://www.youtube.com/watch?v=<video:id>&other_params   
https://www.youtube.com/watch?other_params&v=<video:id>
https://www.youtube.com/watch?other_params&v=<video:id>&more_params  

USAGE FONCTIONNEL

Le plus facile à utiliser le modèle, est l'envelopper dans une fonction comme celle-ci:

/**
 * JavaScript function to match (and return) the video Id
 * of any valid Youtube Url, given as input string.
 * @author: Stephan Schmitz <eyecatchup@gmail.com>
 * @url: https://stackoverflow.com/a/10315969/624466
 */
function ytVidId(url) {
  var p = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;
  return (url.match(p)) ? RegExp. : false;
}

// for example snippet only!
document.body.addEventListener('click', function(e) {
    if (e.target.className == 'yt-url' && 'undefined' !== e.target.value) {
        var ytId = ytVidId(e.target.value);
        alert(e.target.value + "\r\nResult: " + (!ytId ? 'false' : ytId));
    }
}, false);
<!-- Click the buttons to probe URLs -->
<input type="button" value="https://www.youtube.com/watch?v=p-e2G_VcTms&feature=g-logo&context=G29aead6FOAAAAAAABAA" class="yt-url">
<input type="button" value="https://www.youtube.com/latest" class="yt-url">

si le type de la valeur de résultat de la fonction doit être une valeur booléenne, il suffit de remplacer RegExp. par true . C'est tout.

Une dernière remarque sur la vidéo Id longueur : On a demandé si les identifiants ont une longueur fixe de 11 caractères? et si cela pourrait changer dans l'avenir?

la meilleure réponse à cette question est probablement aussi la seule déclaration" officielle "que j'ai trouvé ici et qui dit: " Je ne vois nulle part dans la documentation où nous nous engageons officiellement à une longueur standard de 11 caractères pour les ids Vidéo YouTube. C'est une de ces choses où nous avons une mise en œuvre actuelle, et cela peut rester ainsi indéfiniment. Mais nous n'offrons aucun engagement officiel à ce sujet, alors agissez à vos risques et périls."

167
répondu eyecatchUp 2017-05-23 11:46:56

vous ne pouvez pas associer la partie id avec \w+, car elle n'inclut pas le caractère dash ( -). [A-zA-Z0-9_ -]+ serait quelque chose de plus correct.

4
répondu safdsas 2010-06-30 15:56:12

@eyecatchup ubove a un excellent regex, mais avec l'aide de regexper.com j'ai vu que son regex passera n'importe quelle url youtube où le ?v paramètre a une valeur de n'importe quel mot ou signe répété 11 fois. Mais youtube restreint spécifiquement l'id de la vidéo à 11 caractères donc une correction pour son regex serait

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

comparez la vizualisation de son regex

http://www.regexper.com/#/%5E%28?:https?:%5C/%5C/%29?%28?:www%5C.%29?%28?:youtu%5C.be%5C/%7Cyoutube%5C.com%5C/%28?:embed%5C/%7Cv%5C/%7Cwatch%5C?v=%7Cwatch%5C?.%2b&v=%29%29%28%28%5Cw%7C-%29%7B11%7D%29%28?:%5CS%2b%29?$/

et mon fix

http://www.regexper.com/#%2F%5E(%3F%3Ahttps%3F%3A%5C%2F%5C%2F)%3F(%3F%3Awww%5C.)%3F(%3F%3Ayoutu%5C.be%5C%2F%7Cyoutube%5C.com%5C%2F(%3F%3Aembed%5C%2F%7Cv%5C%2F%7Cwatch%5C%3Fv%3D%7Cwatch%5C%3F.%2B%26v%3D))((%5Ba-zA-Z0-9%5D%7C-)%7B11%7D)(%3F%3A%5CS%2B)%3F%24%2F

comme une édition à le changement de limite de 11 caractères dans le futur alors la regex actuelle signifierait que n'importe quel mot ou - devrait être répété exactement 11 fois, à ce que mon correctif est

/^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11,})(?:\S+)?$/
2
répondu Blagoj Atanasovski 2013-11-28 09:15:41

amélioration pour le grand regex de @eyecatchUp:

  1. ajouter le support pour m.youtube.com domaine
  2. ajouter le support pour youtube-nocookie.com domaine de @Nijikokun
^(?:https?:\/\/)?(?:(?:www|m)\.)?(?:youtu\.be\/|youtube(?:-nocookie)?\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$

Regexper:

http://regexper.com/#%5E(%3F%3Ahttps%3F%3A%5C%2F%5C%2F)%3F(%3F%3A(%3F%3Awww%7Cm)%5C.)%3F(%3F%3Ayoutu%5C.be%5C%2F%7Cyoutube(%3F%3A-nocookie)%3F%5C.com%5C%2F(%3F%3Aembed%5C%2F%7Cv%5C%2F%7Cwatch%5C%3Fv%3D%7Cwatch%5C%3F.%2B%26v%3D))((%5Cw%7C-)%7B11%7D)(%3F%3A%5CS%2B)%3F%24
1
répondu Mrskman 2015-05-29 16:30:40
function get_youtube_video_id_from_url(url){
    var code = url.match(/v=([^&#]{5,})/)
    return (typeof code[1] == 'string') ? code[1] : false;
}
-1
répondu Kirill Artemenko 2013-05-27 22:52:24
function validYT(url) {
  var p = /^(?:https?:\/\/)?(?:www\.)?youtube\.com\/watch\?(?=.*v=((\w|-){11}))(?:\S+)?$/;
  return (url.match(p)) ? RegExp. : false;
}
-4
répondu user1948368 2013-10-07 10:38:22