0

I am using the regex here jQuery Youtube URL Validation with regex

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

It works fine here https://regex101.com/#javascript

But my code is not working- I am using jquery.validate.min.js and additional-methods.js

My code below works fine with other Regexes but with this one is not working, it always says invalid:

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

$("#submit-form").validate({

    // Specify the validation rules
    rules: {
        yturl: {
            required: true,
            minlength: 3,
            pattern: yt
        }

    },
    messages: {
        yturl: {
            pattern: "Wrong url"
        }
    }

Thanks

Community
  • 1
  • 1
user3808307
  • 2,270
  • 9
  • 45
  • 99

1 Answers1

2

Don't use strings and the RegExp() constructor unless you have to. Use a native regular expression literal:

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

The string lexical grammar also recognizes backslash characters as metacharacters, so you have to quote them by doubling them. If you use the notation for a regular expression literal, you don't have to worry about that.

Pointy
  • 405,095
  • 59
  • 585
  • 614