youtube links validation

by zakariamouhid

HTML

<form id="form">
  <label for="pwd">Youtube link:</label>
  <input type="link" id="link" name="link"
         value="https://m.youtube.com/watch?v=5">
  <input type="submit">
</form>

<pre id="pre"></pre>

<script>
  const isValidYT = url => {
    try {
      const u = new URL(url);
      if (/^https?\:$/.test(u.protocol)) {
        if (/^((m|www)\.)?youtube\.com$/.test(u.host)) {
          return /^\/watch\/*$/.test(u.pathname) &&
            u.searchParams.has('v') &&
            /^[a-zA-Z0-9_-]+$/.test(u.searchParams.get('v'));
        } else if (/^youtu\.be$/.test(u.host)) {
          return /^\/[a-zA-Z0-9_-]+\/*$/.test(u.pathname);
        }
      }
    } catch (err) {}
    return false;
  };
	form.onsubmit = e => {
  	if (!isValidYT(link.value)) {
    	e.preventDefault();
    	console.log('not valid');
    }
  };
  link.style.borderStyle = 'solid';
  link.style.borderWidth = '5px';
  link.oninput = () => {
  	link.style.borderColor = isValidYT(link.value) ? '#0f0' : '#f00';
  };
  link.oninput();
  
  const tests = [
    'https://m.youtube.com/watch?v=ab_-123',
    'https://youtube.com/watch?v=ab_-123&pbjreload=101',
    'https://youtu.be/ab_-123',
  ];
  for (const test of tests) {
  	pre.append(test + ' -> ' + isValidYT(test) + '\n');
  }
</script>