Home > Net >  regex works in js but fails in html
regex works in js but fails in html

Time:12-02

I got a regex for matching URIs of YouTube

/^(https:\/\/youtu.be\/|https:\/\/www.youtube.com\/watch\?v=|https:\/\/www.youtube-nocookie.com\/embed\/)([a-zA-Z0-9]{6,12}) /

it works well in js

/^(https:\/\/youtu.be\/|https:\/\/www.youtube.com\/watch\?v=|https:\/\/www.youtube-nocookie.com\/embed\/)([a-zA-Z0-9]{6,12}) /.test('https://www.youtube.com/watch?v=PZP1wGptlUE&list=RDT4X7Ev7RIZA&index=2')
// true

but why it fails in html input[pattern] ?

Please match the requested format

function handle(e) {
  e.preventDefault();
}
<form onsubmit="handle">
  <input placeholder="YouTube URI"
      type="url"
      pattern="^(https:\/\/youtu.be\/|https:\/\/www.youtube.com\/watch\?v=|https:\/\/www.youtube-nocookie.com\/embed\/)([a-zA-Z0-9]{6,12}) " 
      value="https://www.youtube.com/watch?v=PZP1wGptlUE&list=RDT4X7Ev7RIZA&index=2"
      required>
  <button type="submit">submit</button>
</form>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

HTML input patterns have an implicit $ at the end, meaning that it expects to match the entire input.

You're not accounting for the &list=RDT4X7Ev7RIZA&index=2, so it's failing.

You can add something like (\&.*)? to fix it

  • Related